【发布时间】:2021-05-10 11:16:23
【问题描述】:
我在用户和任务之间有多对多的关系。数据透视表充当用户任务的“收件箱”视图,并被定义为自定义模型,这很好......
public function tasks()
{
return $this->belongsToMany(Task::class, 'inbox_messages')
->withPivot('read', 'pinned', 'suggested', 'last_viewed_at')
->withTimestamps()
->using(Inbox::class)
->as('inbox');
}
但是,当我想查询Tasks时,我在查询数据透视表时感觉有点受限...
例如,我想查询今天查看并固定的任务...
$tasks = Auth::user()->tasks()
->wherePivot('pinned', true)
->wherePivot('last_viewed_at', Carbon::today)
->get();
但我实际上希望能够编写如下,重用本地范围我已经在我的收件箱数据透视模型上定义...
$tasks = Auth::user()->tasks()
->wherePivotPinned()
->wherePivotViewedToday()
->get();
最好是这样,在 Builder 方法中使用 pivot 访问器...
$tasks = Auth::user()->tasks()
->whereInboxPinned()
->whereInboxViewedToday()
->get();
也许已经有可能但没有记录?
如果没有,这个功能如何实现?
【问题讨论】:
标签: laravel eloquent many-to-many pivot-table