2013-02-17 233 views
0

我在想如何在雄辯中執行子查詢。這裏是包含我想要執行的子查詢和我正在使用雄辯模型結構的數據庫的要點。使用laravel雄辯的mysql子查詢

//the query I want to execute 
select p.title, c.total 
from posts as p, 
(select post_id as id, count(*) as total from comments group by post_id) as c 
where p.id=c.id 


//my table structures 
table posts - 
id title content 

table comments - 
id post_id content 


//eloquent models 
class Post extends Eloquent{ 
    public static $timestamps = false; 

    public function comments(){ 
     return $this->has_many('Comment', 'post_id'); 
    } 
} 

class Comment extends Eloquent{ 
    public static $timestamps = false; 

    public function post(){ 
     return $this->belongs_to('Post', 'post_id'); 
    } 
} 

基本上我想用雄辯來執行包含子查詢的查詢。我知道我可以使用DB :: query();方法來執行原始查詢或可能嘗試使用加入,但我想堅持雄辯。任何類型的架構建議都會受到歡迎,因爲我可能會錯過一種可以使用雄辯的方式獲得相同結果而不使用完全相同查詢的方式。

在此先感謝。

+1

我不認爲這是可能的。沒有辦法。 – Gargron 2013-02-17 19:20:27

+0

您將不得不創建自定義類方法並使用流暢的查詢構建器。這不會是你想要的,但會做你需要的。查看[Fluent查詢生成器](http://laravel.com/docs/database/fluent#aggregates) – Cristian 2013-02-18 17:18:56

+2

另一個得到評論數的方法是'Post :: with('comments')'然後使用php在視圖上使用'count()'方法。 – Cristian 2013-02-18 17:20:48

回答

0

可能到目前爲止,在Eloquent中沒有子查詢支持。然而,你可以嘗試:

  1. 執行子查詢,並把結果放在一個臨時表中,然後執行指的是表中的主查詢(不要忘記刪除臨時表)
  2. 重寫查詢中一種不需要使用子查詢的方式(我認爲這並不總是可行的)。

對於第二種替代你的查詢將變成:

select p.title, count(c.id) as total 
    from posts as p 
    left join comments as c on p.id=c.id 
group by p.id 

,我認爲這是相當的,通常速度更快。

PS:我沒有測試過查詢,因爲我沒有表格,但我經常使用這種方法。如果有任何錯字,請讓我知道。

+0

感謝您的幫助,但我已經改變了一點體系結構,並從流利的查詢構建器實現了join()方法。我現在正想要它:D再次感謝 – 2013-02-25 15:27:52