Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from multiple tables with laravel fluent query builder

Tags:

php

mysql

laravel

I'm re-writing some PHP/MySQL to work with Laravel. One thing I would like to do is make the DB queries more succinct with the Fluent Query Builder but I'm a bit lost:

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

This queries a phpbb forum and gets posts: enter image description here

How could I re-write this to make use of the Fluent Query Builder syntax?

like image 872
Simon Smith Avatar asked Jan 22 '13 16:01

Simon Smith


2 Answers

Not tested but here is a start

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'
    ));
like image 86
itachi Avatar answered Oct 14 '22 16:10

itachi


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();
like image 5
user3967434 Avatar answered Oct 14 '22 17:10

user3967434