【问题标题】:Laravel foreach "where" with eloquentLaravel foreach 用雄辩的“where”
【发布时间】:2014-11-25 04:09:44
【问题描述】:

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

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();

**这就是我所拥有的**

    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();

【问题讨论】:

  • 这是 php……你不能空着写-&gt;where。应该是这里的对象。
  • 你能给我看一个简短的例子来说明我如何做到这一点吗?谢谢
  • 例如:$query-&gt;where($field, $value);

标签: laravel laravel-4 eloquent


【解决方案1】:

这样的事情应该可以工作:

$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();

【讨论】:

  • 完美运行!非常感谢!
【解决方案2】:
$query = Listing::where('id', $id);
$i = 0;
foreach ($input as $key => $value) {
     $i++;
     $query->where('field_'.$i,$value.'_'.$i);
}
return $query->get();

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

类似:

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

大致翻译为:

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

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 2017-11-05
    • 2016-06-24
    • 2014-11-09
    • 2017-06-26
    • 2021-09-29
    • 2016-07-05
    • 1970-01-01
    相关资源
    最近更新 更多