ponich / eloquent-traits
用于Laravel Eloquent模型的特性
1.0.3
2018-07-12 17:24 UTC
Requires
- php: >=7.1
- illuminate/support: 5.5.*|5.6.*
Requires (Dev)
- laravel/framework: 5.5.*|5.6.*
- mockery/mockery: ~1.0
- orchestra/testbench: ~3.3.0|~3.4.2|^3.5.0
- phpunit/phpunit: ~7.0
Suggests
- ext-pdo_sqlite: For SQLite database for tests
This package is not auto-updated.
Last update: 2024-09-27 23:14:50 UTC
README
此包增加了在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') );