如何在Laravel 5中使用雄辩的方法从3表中获取一些数据? 我有3个表,列表,卡,用户
列表模型
public function card()
{
return $this->hasMany(Card::class);
}
卡型号
public function lists()
{
return $this->belongsTo(Lists::class);
}
public function member()
{
return $this->belongsToMany(User::class)->withPivot('status','user_role')->withTimestamps();
}
用户模型
public function card_member(){
return $this->belongsToMany(Card::class)->withTimestamps();
}
我想在分配给特定用户的卡中获取列表(例如user_id:2)
喜欢这个JSOn数据
{
"id": 2,
"boards_id": "1",
"list_name": "List 2 B1 U1",
"position": 2,
"created_at": "2019-04-03 16:02:03",
"updated_at": "2019-04-03 16:02:03",
"card": [
{
"id": 8,
"lists_id": "2",
"card_title": "Card 3 L2",
"labels": null,
"description": null,
"start_card": null,
"end_card": null,
"position": 2,
"is_archieved": false,
"created_at": "2019-04-26 15:34:22",
"updated_at": "2019-04-26 15:34:22"
},
{
"id": 9,
"lists_id": "2",
"card_title": "Card 4 L2",
"labels": null,
"description": null,
"start_card": null,
"end_card": null,
"position": 3,
"is_archieved": false,
"created_at": "2019-04-26 15:34:25",
"updated_at": "2019-04-26 15:34:25"
}
表结构: 列表:
id
boards_id
listname
position
卡:
id
lists_id
card_title
Card_user(数据透视表):
id
card_id
user_id
答案 0 :(得分:0)
让关系名称从“ member”更改为“ members”,因为这是多对多关系。
public function members()
{
return $this->belongsToMany(User::class)->withPivot('status','user_role')->withTimestamps();
}
您可能会说:
$userId = 2;
$lists = List::with([
'card' => function ($query) {
$query->whereHas('members', function ($query) user ($userId) {
$query->whereKey($userId);
})
}
])
->whereHas('card.members', function ($query) use ($userId) {
$query->whereKey($userId);
})
->get();
所以我们只渴望加载用户ID为2的卡。