Laravel whereNotIn和哪里没有一起工作

时间:2015-01-13 10:10:08

标签: php laravel eloquent

我有一个涉及以下几行的功能:

$products_to_ignore = $this->products()->get()->lists('id'); // returns [1,3,5]
$products = Product::
      whereNotIn('id', $products_to_ignore)
    ->where('stock_level', '>', 0)
    ->with('producer')
    ->get();
return $products;

我在下面的行中有一个数据库表

id    product_name    stock_level
1     eggs            5
2     cheese          0  
3     milk            1
4     cucumber        4   
5     pie             0

但上面的函数返回[]

如果我只是使用

$products = Product::
      where('stock_level', '>', 0)
    ->with('producer')
    ->get();
return $products;

我会得到[1,3,4],如果我使用:

$products_to_ignore = $this->products()->get()->lists('id'); // returns [1,3,5]
$products = Product::
      whereNotIn('id', $products_to_ignore)
    ->with('producer')
    ->get();
return $products;

我会得到[2,4]

为什么这两个人不能很好地在一起玩?如何获取库存水平大于0的项目,这些项目也不在数组[1,3,5]中?例如,此问题中的第一段代码应返回产品[4],而不是数组中的库存级别> 0

1 个答案:

答案 0 :(得分:0)

您有两个where条件彼此相邻。也许and会调和它们;)

$products_to_ignore = $this->products()->get()->lists('id'); // returns [1,3,5]
$products = Product::where('stock_level', '>', 0,'AND')
    ->whereNotIn('id', $products_to_ignore)
    ->with('producer')
    ->get();
return $products;

根据API,\ vendor \ laravel \ framework \ src \ Illuminate \ Database \ Query \ Builder.php第773行:

/**
 * Add a "where not in" clause to the query.
 *
 * @param  string  $column
 * @param  mixed   $values
 * @param  string  $boolean
 * @return \Illuminate\Database\Query\Builder|static
 */
public function whereNotIn($column, $values, $boolean = 'and')
{
    return $this->whereIn($column, $values, $boolean, true);
}
相关问题