2013-02-17 235 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