huboshen / laravel-one-to-many-sync
允许Laravel的Has Many和Morph Many关系进行同步方法。
v1.0.0
2020-04-26 02:41 UTC
This package is auto-updated.
Last update: 2024-09-26 15:42:31 UTC
README
允许Laravel的HasMany和MorphMany关系进行同步方法。
先决条件
Laravel 5或以上版本应该没问题。
安装
composer require huboshen/laravel-one-to-many-sync
更新composer后,将服务提供者添加到config/app.php中的providers数组中
Huboshen\OneToManySync\OneToManySyncServiceProvider::class,
Laravel 5.5(或更高版本)使用包自动发现,因此不需要手动添加ServiceProvider。
使用
在Laravel中同步hasMany关系
当一篇帖子通过hasMany关系拥有多个评论时
class Post extends Model { protected $fillable = ['title']; public $timestamps = true; /** * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function comments() { return $this->hasMany(Comment::class); } }
使用"sync_one_to_many"方法同步帖子与这些评论
$post->comments()->sync_one_to_many([ ['id' => 1, 'body' => 'update the comment where id = 1'], ['body' => 'this is a new comment without a id yet'], ]);
结果,无论帖子最初有多少评论,帖子最终将只剩下两个评论
- id为1的评论,其"body"字段更新如上。
- 一个新评论,其"body"字段为"这是一个没有id的新评论"。
在同步时不想删除任何内容吗?
没问题。只需将false作为第二个参数传递,以指示是否启用删除行为(默认为true)。
$post->comments()->sync_one_to_many([ ['id' => 1, 'body' => 'update the comment where id = 1'], ['body' => 'this is a new comment without a id yet'], ], false);
在同步时不想更新父模型的时间戳吗?
没问题。只需将false作为第三个参数传递,以指示是否启用父级更新(默认为true)。
$post->comments()->sync_one_to_many([ ['id' => 1, 'body' => 'update the comment where id = 1'], ['body' => 'this is a new comment without a id yet'], ], true, false);
在Laravel中同步morphMany关系
当一篇帖子通过morphMany关系拥有多个评论时
class PostPoly extends Model { protected $table = "posts_poly"; protected $fillable = ['title']; /** * Get all of the post's comments. */ public function comments() { return $this->morphMany('App\Models\CommentPoly', 'commentable'); } }
使用"sync_one_to_many_morph"方法同步帖子与这些评论
$post->comments()->sync_one_to_many_morph( [ ['id' => 1, 'body' => 'update the comment where id = 1'], ['body' => 'this is a new comment without a id yet'], ]);
结果将与之前的hasMany示例类似。
"sync_one_to_many_morph"方法的第二个参数用于控制删除,第三个参数用于控制父级更新。
许可证
本项目采用MIT许可证 - 有关详细信息,请参阅LICENSE.md文件。