【问题标题】:How do I take the last so many entries (skip) with Eloquent Query Builder in Laravel如何在 Laravel 中使用 Eloquent Query Builder 获取最后这么多条目(跳过)
【发布时间】:2014-03-05 12:35:56
【问题描述】:

我正在尝试使用 Eloquent 在 Laravel 中编写一个查询,但只需要其中的最后 5 个正在进行的字段。这是查询:

    public static function past_profile_fan_likes($id) {
        $latest_profile_fan_likes = DB::table('fanartists')
                    ->join('artists', 'fanartists.artist_id', '=', 'artists.id')
                    ->orderBy('fanartists.created_at', 'DESC')
                    ->skip(4)
                    ->where('fanartists.fan_id', '=', $id)
                    ->select('artists.id', 'artists.fbid', 'artists.stage_name', 'artists.city', 'artists.state', 'artists.image_path', 'artists.description')
                    ->get();


        return $latest_profile_fan_likes;

    }

当我调用这个时,我收到了这个错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'offset 4' at line 1 (SQL: select `artists`.`id`, `artists`.`fbid`, `artists`.`stage_name`, `artists`.`city`, `artists`.`state`, `artists`.`image_path`, `artists`.`description` from `fanartists` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` where `fanartists`.`fan_id` = ? order by `fanartists`.`created_at` desc offset 4) (Bindings: array ( 0 => '1', ))

我在这里做错了吗?跳过使用可能有问题?谢谢你的帮助。

【问题讨论】:

    标签: mysql laravel laravel-4 eloquent


    【解决方案1】:

    您需要添加一个take 查询,以便它添加一个LIMIT 查询并将其转换为正确的语法;

    DB::table('fanartists')
    ->join('artists', 'fanartists.artist_id', '=', 'artists.id')
    ->orderBy('fanartists.created_at', 'DESC')
    ->skip(4)
    ->take(100)
    ->where('fanartists.fan_id', '=', $id)
    ->select('artists.id', 'artists.fbid', 'artists.stage_name', 'artists.city', 'artists.state', 'artists.image_path', 'artists.description')
    ->get();
    

    如果使用偏移量,您将需要提供限制,即使您不想限制。见这里:http://dev.mysql.com/doc/refman/5.0/en/select.html#id4651990

    【讨论】:

    • 有没有办法提供一个足够大的限制来处理任意数量的条目?
    【解决方案2】:

    这看起来更像流利的,我不太熟悉。但是,如果您使用 Eloquent 定义了模型和关系,如果您只想获取最后 5 条记录,则可以颠倒顺序并 take(5):
    像这样……

    $latest_profile_fan_likes = fanartists::with('artists')->where('fan_id', '=', $id)->orderBy('created_at', 'ASC')->take(5)->get('id', 'fbid' .......);

    【讨论】:

    • 我不想要最后 5 条记录,我想要前 4 条之后的所有记录。所以记录 5 条到多条记录。
    • 啊,好的。您的 skip() 在您的 where() 之前的逻辑中指示。根据你得到的错误(偏移量),将它移到你的 where 子句之后。
    猜你喜欢
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2019-08-11
    • 2020-04-26
    • 1970-01-01
    • 2015-06-15
    相关资源
    最近更新 更多