ponich/eloquent-traits

用于Laravel Eloquent模型的特性

1.0.3 2018-07-12 17:24 UTC

This package is not auto-updated.

Last update: 2024-09-27 23:14:50 UTC


README

Build Status License Latest Stable Version Total Downloads

此包增加了在Laravel Eloquent模型中使用特性的能力

特性列表

安装

此包可以在Laravel 5.5或更高版本中使用。

composer require ponich/eloquent-traits

您可以使用以下命令发布迁移:

php artisan vendor:publish --provider="Ponich\Eloquent\Traits\ServiceProvider" --tag="migrations"

迁移发布后,您可以运行迁移来创建表:

php artisan migrate

特性

虚拟属性

为模型添加创建虚拟属性的能力。

使用特性:\Ponich\Eloquent\Traits\VirtualAttribute

示例

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use \Ponich\Eloquent\Traits\VirtualAttribute;

    protected $table = 'posts';

    protected $guarded = ['id'];

    public $virtalAttributes = ['tags', 'og_tags'];
}

在类的$virtalAttributes属性中列出所有有效的虚拟属性。

$post = Post::firstOrFail(1);

$post->tags = ['tag1', 'tag2', 'tag3'];
$post->save();

$post->refresh();

var_dump($post->tags); 
/**
    array(3) {
      [0]=>
      string(4) "tag1"
      [1]=>
      string(4) "tag2"
      [2]=>
      string(4) "tag3"
    }
*/

附件

允许将文件链接到模型

使用特性:\Ponich\Eloquent\Traits\HasAttachment

示例

模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use \Ponich\Eloquent\Traits\HasAttachment;

    protected $table = 'posts';

    protected $guarded = ['id'];
}

添加附件

$post = Post::findOrFail(1);

// by path
$post->attach('/path/to/file');

// by request
$post->attach(
    $request->file('photo')
);