troelskn/laravel-fillable-relations
Composer 安装命令:
composer require troelskn/laravel-fillable-relations
包简介
Provides HasFillableRelations trait to Eloquent models
README 文档
README
This library provides a trait for mixing in to an Eloquent Model. Doing so will enable support for fillable relations.
To use, first require in your composer file:
composer require troelskn/laravel-fillable-relations
Then, in your code:
<?php namespace MyApp\Models; use Illuminate\Database\Eloquent\Model; use LaravelFillableRelations\Eloquent\Concerns\HasFillableRelations; class Foo extends Model { use HasFillableRelations; protected $fillable_relations = ['bar']; function bar() { return $this->hasOne(Bar::class); } } class Bar extends Model { use HasFillableRelations; protected $fillable_relations = ['foos']; function foos() { return $this->hasMany(Foo::class); } }
And you can now fill relations, like so:
$foo = new Foo( [ 'cuux' => 42, 'bar' => [ 'id' => 42 ] ] );
Or perhaps:
$foo = new Foo( [ 'cuux' => 42, 'bar' => [ 'name' => "Ye Olde Pubbe" ] ] );
And also:
$bar = new Bar( [ 'name' => "Ye Olde Pubbe", 'foos' => [ [ 'cuux' => 42 ], [ 'cuux' => 1337 ] ] ] );
In order to automatically detach empty relations, pass an empty array:
$bar->fill([ 'foos' => [] // Detach all foos ]); $bar->save();
You can use Laravel validator array rule to preserve empty arrays passed to the request:
class UpdateRequest extends FormRequest { public function rules() { return [ 'foos' => [ 'array', ], ]; } }
And then update attributes and relations in one line in the controller:
public function update(UpdateRequest $request, Bar $bar) { $bar->fill($request->validated())->save(); }
统计信息
- 总下载量: 66.98k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 65
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-01-01