[英]Laravel multiple pivot relationship
I'm struggling with creating a relationship between two pivots that share single model. 我正在努力创建共享单个模型的两个枢轴之间的关系。
The pivots in question are item_tag and playlist_tag. 有问题的数据中心是item_tag和playlist_tag。 Below I have described the table and the relationships I have created already. 下面,我描述了表和已经创建的关系。
So i can currently get items for playlists, playlists for items, tags for items, tags for playlists. 因此,我目前可以获取播放列表的项目,播放列表的项目,项目的标签,播放列表的标签。
What i'm struggling to do is : 我正在努力做的是:
I believe this may be done with a 'manyThrough' but honestly i'm lost. 我相信这可以通过“ manyThrough”完成,但老实说我迷路了。
Some more relationship detail 更多关系细节
Tags can be applied to both playlists and items 标签可同时应用于播放列表和项目
Example table structure 表结构示例
Table : items
id
name
Table : playlists
id
name
Table : item_playlist
item_id
playlist_id
Table : tags
id
name
Table : item_tag
item_id
tag_id
Table : playlist_tag
playlist_id
tag_id
Example class / relationship structure 示例类/关系结构
class Playlist extends Model
{
public function items()
{
return $this->belongsToMany(Item::class)->withTimestamps();
}
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
}
...
class Item extends Model
{
public function playlists()
{
return $this->belongsToMany(Playlist::class)->withTimestamps();
}
public function tags()
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
}
...
class Tag extends Model
{
public function items()
{
return $this->belongsToMany(Item::class)->withTimestamps();
}
public function playlists()
{
return $this->belongsToMany(Playlist::class)->withTimestamps();
}
}
Getting the items that share at least one tag with a given playlist: 获取与给定播放列表共享至少一个标签的项目:
$tags = $playlist->tags()->pluck('id');
$items = Item::whereHas('tags', function($query) use($tags) {
$query->whereIn('id', $tags);
})->get();
Getting the items that share all the tags with a given playlist: 获取与给定播放列表共享所有标签的项目:
$tags = $playlist->tags()->pluck('id');
$items = Item::whereHas('tags', function($query) use($tags) {
$query->whereIn('id', $tags);
}, '=', $tags->count())->get();
The reverse direction works the same way. 反向的工作方式相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.