2013-01-22 27 views
6

Tôi đang viết lại một số PHP/MySQL để làm việc với Laravel. Một điều tôi muốn làm là làm cho DB truy vấn gọn gàng hơn with the Fluent Query Builder nhưng tôi một chút mất:Chọn từ nhiều bảng với trình tạo truy vấn thông thạo laravel

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 

này truy vấn một diễn đàn phpbb và được bài viết: enter image description here

Làm thế nào tôi có thể tái viết điều này để sử dụng cú pháp Trình tạo truy vấn thông thạo?

Trả lời

18

Không thử nghiệm nhưng đây là một sự khởi đầu

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' 


         )); 
+0

Ah, không biết bạn có thể chuỗi tham gia. Hữu ích, cảm ơn. –

+0

Có một tùy chọn như dưới đây (thử nghiệm trong 5.3) - -> get (array ('phpbb_topics *', 'username', 'phpbb_posts.post_text' ) – Sadat

2

xem xét cố gắng mã này. Nó sẽ hoàn thành những gì bạn cần hoàn thành.

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")); 
+1

Đối với không nói tiếng Anh, bạn dường như đã được chẩn đoán vấn đề tốt: P – rayryeng

1
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(); 
Các vấn đề liên quan