使用laravel fluent查询生成器从多个表中进行选择

时间:2013-01-22 16:58:18

标签: php mysql laravel

我正在重写一些PHP / MySQL以与Laravel一起工作。我想做的一件事是让数据库查询更简洁with the Fluent Query Builder,但我有点迷失:

SELECT p.post_text, p.bbcode_uid, u.username, t.forum_id, t.topic_title, t.topic_time, t.topic_id, t.topic_poster
FROM phpbb_topics t, phpbb_posts p, phpbb_users u
WHERE t.forum_id = 9
AND p.post_id = t.topic_first_post_id
AND u.user_id = t.topic_poster
ORDER BY t.topic_time
DESC LIMIT 10

这会查询phpbb论坛并获取帖子: enter image description here

如何重新编写此代码以使用Fluent Query Builder语法?

3 个答案:

答案 0 :(得分:21)

未经测试,但这是一个开始

return DB::table('phpbb_topics')
    ->join('phpbb_posts', 'phpbb_topics.topic_first_post_id', '=', 'phpbb_posts.post_id')
    ->join('phpbb_users', 'phpbb_topics.topic_poster', '=', 'phpbb_users.user_id')
    ->order_by('topic_time', 'desc')
    ->take(10)
    ->get(array(
        'post_text',
        'bbcode_uid',
        'username',
        'forum_id',
        'topic_title',
        'topic_time',
        'topic_id',
        'topic_poster'
    ));

答案 1 :(得分:3)

return DB::table(DB::raw('phpbb_topics t, phpbb_posts p, phpbb_users u')) 
->select(DB::raw('p.post_text, p.bbcode_uid, u.username, t.forum_id, t.topic_title, t.topic_time, t.topic_id, t.topic_poster'))
->where('phpbb_topics.topic_first_post_id', '=', 'phpbb_posts.post_id')
->where('phpbb_users', 'phpbb_topics.topic_poster', '=', 'phpbb_users.user_id')
->order_by('topic_time', 'desc')->take(10)->get();

答案 2 :(得分:2)

考虑尝试此代码。它应该完成你需要完成的任务。

DB::select(DB::raw("SELECT p.post_text, p.bbcode_uid, u.username, t.forum_id, t.topic_title, t.topic_time, t.topic_id, t.topic_poster
FROM phpbb_topics t, phpbb_posts p, phpbb_users u
WHERE t.forum_id = 9
AND p.post_id = t.topic_first_post_id
AND u.user_id = t.topic_poster
ORDER BY t.topic_time
DESC LIMIT 10"));