我试图在某些标签上过滤我的模型。我目前有这个代码:
$letters = \App\Letter::with(['tags' => function($query) {
foreach(\Cookie::get('tags') as $tag => $name) {
$query->where('tags.id', $tag);
}
}])->orderBy('created_at', 'desc')->where('service','send')->where('mailbox_id', '=', Auth::user()->activeMailboxId)->paginate(8);
我希望获得所有带有关系标签的字母,以便我可以循环遍历cookie并动态添加where语句。但是,它不仅仅返回带有cookie数组的标签的字母,而是返回附加到我的帐户的所有字母,任何人都知道如何执行此操作?
谢谢!
答案 0 :(得分:1)
您可以使用WhereIn
来发送包含获取数据所需的ID的数组,试试这个,
$letters = \App\Letter::with(['tags' => function($query) {
//$tag array should be like this == [4,5,6]
$query->whereIn('id', $tag);
}])->orderBy('created_at', 'desc')
->where('service','send')
->where('mailbox_id', '=', Auth::user()
->activeMailboxId)
->paginate(8);
你也可以这样试试
$letters = \App\Letter::with('tags')
->whereHas('tags',function($query) {
//$tag array should be like this == [4,5,6]
$query->whereIn('id', $tag);
})->orderBy('created_at', 'desc')
->where('service','send')
->where('mailbox_id', '=', Auth::user()
->activeMailboxId)
->paginate(8);
希望这有帮助!