【问题标题】:how do i convert SQL query to laravel Eloquent?如何将 SQL 查询转换为 laravel Eloquent?
【发布时间】:2021-04-19 16:19:04
【问题描述】:

我想要做的是转换这个查询,我想使用分页但是当我使用像这个分页这样的查询时不起作用

 DB::select('SELECT *, ( ( weight * 400 ) + Making_charge) AS Sum FROM products WHERE '.$cat.' ='. $id.' ORDER BY sum ASC');

当我尝试使用分页时,我得到了这个错误

Call to a member function links() on array (View: 

我尝试过类型转换,但也没有用

谁能在不讨厌的情况下给我提供正当的理由或解决方案 谢谢

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    您得到Call to a member function links() on array 的原因是 QueryBuilder 返回一个数组。不像 Eloquent 那样合集。

    我将您的 SQL 查询更改为使用双引号以使用字符串插值,并将工作 sum 更改为 product_sum,因为 sum 是 mysql 的保留字。

    "SELECT *, (( weight * 400 ) + making_charge) as product_sum FROM products WHERE {$cat} = {$id} ORDER BY product_sum ASC";
    

    您使用 eloquent 的查询将如下所示:

    Product::query()
        ->where($cat, $id)
        ->select(['*', DB::raw('(weight * 400 + making_charge) as product_sum')])
        ->orderBy('product_sum')
        ->get();
    

    此查询返回一个集合。您也可以使用 laravel 分页进行分页:

    $items_per_page = 10;
    
    Product::query()
        ->where($cat, $id)
        ->select(['*', DB::raw('(weight * 400 + making_charge) as product_sum')])
        ->orderBy('product_sum') // The default direction is ASC
        ->paginate($items_per_page);
    

    【讨论】:

    • 你太棒了,谢谢你
    猜你喜欢
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2022-07-29
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多