首页 > 解决方案 > 动态加载标签并在模型中过滤它们

问题描述

我正在尝试在与其相关的某些标签上过滤我的模型。我目前有这个代码:

    $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 数组标签的字母,而是返回附加到我的帐户的所有字母,有人知道如何做到这一点吗?

谢谢!

标签: laravelcookieseloquent

解决方案


您可以使用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);

希望这可以帮助!


推荐阅读