繁体   English   中英

Laravel Eloquent函数不起作用(?)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM