![](/img/trans.png)
[英]Laravel Eloquent with() method works with 'where' but doesn't work with 'Model::find()'
[英]Laravel Eloquent where function doesn't work(?)
如果得到以下数据库表:
现在,我要显示“ inventory_warning”比“ inventory”字段大的行。 像第二个结果一样,如下所示:
在我的第一个示例中,我使用Eloquent编写了where语句,并尝试获取行,但是它不会产生正确的结果(它将检索所有行)。 我的第二个示例显示了使用PHP-if语句完成的检查,该语句有效,但是当表中包含更多数据时,效率将非常低。
缩短代码:
<?php $products = Product::where('inventory_warning', '>', 'inventory')->get();?>
<tr>
<th colspan="3">First results:</th>
</tr>
@foreach($products as $product)
<tr>
<td># {{ $product->id }} - {{$product->item->name}}</td>
<td>{{ $product->inventory }}</td>
<td>{{ $product->inventory_warning }}</td>
</tr>
@endforeach
<?php $products = Product::all();?>
<tr>
<th colspan="3">Second results:</th>
</tr>
@foreach($products as $product)
@if($product->inventory_warning > $product->inventory)
<tr>
<td># {{ $product->id }} - {{$product->item->name}}</td>
<td>{{ $product->inventory }}</td>
<td>{{ $product->inventory_warning }}</td>
</tr>
@endif
@endforeach
这里发生了什么? 这可能是雄辩的错误,还是我做错了什么?
据我所知, where
函数不支持比较两个数据库字段。 您必须使用whereRaw
Product::whereRaw('inventory_warning > inventory')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.