laravel - 动态加载标签并在模型中过滤它们
问题描述
我正在尝试在与其相关的某些标签上过滤我的模型。我目前有这个代码:
$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 数组标签的字母,而是返回附加到我的帐户的所有字母,有人知道如何做到这一点吗?
谢谢!
解决方案
您可以使用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);
希望这可以帮助!
推荐阅读
- html - 弹性基础:自动在 IE11 中不起作用
- sql - 每次修改表时运行脚本
- node.js - 如何在 React 中使用使用“window”引用的组件与服务器端渲染?
- c# - 使用 Func 和 Expression Func 运行查询之间的差异
- javascript - 如何使用 HTML、CSS、Javascript 在可编辑字段中垂直键入文本...?
- jenkins - 詹金斯的 currentBuild()
- python - PIL 绘制没有灰色轮廓的文本
- intellij-idea - 默认在带有单词边界的路径中查找
- php - 在 Netbeans 8.2 中调试期间为空调用堆栈
- javascript - javascript forEach() 函数如何在 mongodb shell 中迭代文档?