Laravel foreach "where" with eloquent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27118668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:28:14  来源:igfitidea点击:

Laravel foreach "where" with eloquent

laravellaravel-4eloquent

提问by Amila Hyman

I have certain fields and data values which cannot be hardcoded into the query. I'm trying to get something like this:

我有某些无法硬编码到查询中的字段和数据值。我试图得到这样的东西:

return Listing::where('id', $id)
            ->where(function($query) use ($input) {
                 ->where('field_1', 'foo_1')
                 ->where('field_2', 'foo_2')
                 ->where('field_3', 'foo_3') 
            }
            ->get();

**Here's what I have **

**这是我所拥有的**

    return Listing::where('id', $id)
        ->where(function($query) use ($input) {
            $i = 0;
            foreach ($input as $key => $value) {
                $i++;
                // ->where('field_1', red_1); // Desired output
                ->where("where(field_{$i},".$value."_1)");
                // $query = $query."where(field_{$i},".$value."_1)"."<br>";
                // return $query prints out the following
                /*
                    field_1 red_1,
                    field_2 foo_1,
                    field_3 bar_3
                */
            }
        })
        ->get();

回答by Alexander Kerchum

Something like this should work:

这样的事情应该工作:

$listing = Listing:where('id', $id);
foreach ($input as $key => $value) {
     $i++;
     // ->where('field_1', red_1); // Desired output
     $listing->where("where(field_{$i},".$value."_1)");
}
$results = $listing->get();

回答by turntwo

$query = Listing::where('id', $id);
$i = 0;
foreach ($input as $key => $value) {
     $i++;
     $query->where('field_'.$i,$value.'_'.$i);
}
return $query->get();

One you're not chaining correctly and two you are mis-using the querybuilder closure. If you want to execute logic like a loop then you have to break down the query. Furthermore using a where closure is like writing a parenthesis around your where conditions.

一个你没有正确链接,两个你错误地使用了 querybuilder 闭包。如果您想像循环一样执行逻辑,那么您必须分解查询。此外,使用 where 闭包就像在你的 where 条件周围写一个括号。

Something like:

就像是:

  $query->where('bacon', $foo)
  $query->where(function ($query) use ($bar, $baz){
       $query->where('apple', $bar);
       $query->orWhere('orange', $baz)
  });

Would roughly translate to:

大致翻译为:

  WHERE bacon = $foo AND (apple = $bar OR orange = $baz)