如何使用Laravel中的Eloquent Query Builder获取最后这么多条目(跳过)

时间:2014-02-07 22:26:58

标签: mysql laravel laravel-4 eloquent

我正在尝试使用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', ))

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

2 个答案:

答案 0 :(得分:3)

您需要添加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

答案 1 :(得分:0)

这看起来更像流利,我不太熟悉。但如果您使用Eloquent定义了您的模型和关系,您可以撤消订单并采取(5)如果您只想获取最后5条记录:
像这样...

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