【问题标题】:Multiple Where Statements from Loop in Callback Function in Laravel/EloquentLaravel/Eloquent 回调函数中来自循环的多个 Where 语句
【发布时间】:2021-09-15 21:23:26
【问题描述】:

我正在尝试构建一个过滤函数,该函数会根据用户选择的功能返回交换列表。每个特性都有一个唯一的 slug,$featureSlugs 包含这些 slug(字符串)的数组。

$featureSlugs = ['security', 'mobile-app', '2FA'];

$exchanges = Exchange::whereHas('features', function ($q) use ($featureSlugs) {
                    $q->where('slug', $featureSlugs);
                })->get();

非常奇怪的是,此查询适用于 1 个或 2 个功能,但超过 2 个的任何内容都停止工作并且不再过滤。

我希望过滤器越来越窄,因此对每个功能使用多个 where 语句,只返回包含用户选择的所有功能的交换。这是我正在尝试的代码,但它不起作用,但我认为演示了我正在尝试做的事情:

$exchanges = Exchange::whereHas('features', function ($q) use ($featureSlugs) {
                    foreach($featureSlugs as $featureSlug)
                    {
                        $q->where('slug', $featureSlug);
                    }
                })->get();

如何为数组中的每个 featureSlug 放置多个 where 语句?

【问题讨论】:

  • 我的建议是你不要这样做,最好事先检查 slugs 然后使用条件whereIn('slug', $array_of_slugs)
  • whereIn 的问题是它将返回列表中至少包含 1 个功能的任何交换,而不是仅与所有 3 个功能交换

标签: php laravel eloquent


【解决方案1】:

用这种方法试试。

$featureSlugs = ['security', 'mobile-app', '2FA'];

$exchanges = Exchange::whereHas('features', function ($query) use ($featureSlugs) {
    $query->distinct()->whereIn('slug', $featureSlugs);
}, '=', count($featureSlugs))->get();

【讨论】:

  • 太棒了!这行得通!这是我认为最干净的解决方案。
  • 是的,我喜欢人们标记一个可行的解决方案。
【解决方案2】:

你的方向是对的。你只需要使用whereInorWhere

$exchanges = Exchange::whereHas('features', function ($q) use ($featureSlugs) {
    $q->whereIn('slug', $featureSlugs);

    // This one is not optimal of course
    foreach($featureSlugs as $featureSlug) {
        $q->orWhere('slug', $featureSlug);
    }
})->get();

【讨论】:

    【解决方案3】:

    你可以这样做:

    $featureSlugs = ['security', 'mobile-app', '2FA'];
    
    $exchanges = Exchange::whereHas('features', function ($q) use ($featureSlugs) {
                    foreach($featureSlugs as $featureSlug)
                    {
                        $q->where('slug', $featureSlug);
                    }
                })-with(['features'=> function ($q) use ($featureSlugs) {
                    foreach($featureSlugs as $featureSlug)
                    {
                        $q->where('slug', $featureSlug);
                    }
                }])->get();
    

    【讨论】:

      猜你喜欢
      • 2013-10-29
      • 2019-11-27
      • 2014-10-16
      • 2018-07-11
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      相关资源
      最近更新 更多