使用laravel的eloquent的mysql子查询

时间:2013-02-17 19:18:19

标签: mysql laravel eloquent

我想知道如何以雄辩的方式执行子查询。这里是包含我想要执行的子查询以及我正在使用的具有雄辩模型结构的数据库的要点。

//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');
    }
}

基本上我想用eloquent来执行包含子查询的查询。我知道我可以使用DB :: query();执行原始查询的方法或可能尝试使用join但我想坚持口才。任何类型的建筑建议都受到欢迎,因为我可能会错过一种方法,可以使用eloquent来获得相同的结果而不使用完全相同的查询。

提前感谢。

1 个答案:

答案 0 :(得分:0)

可能到目前为止,Eloquent中没有子查询支持。但是你可以尝试:

  1. 执行子查询并将结果放在临时表中,然后执行引用该表的主查询(不要忘记删除临时表)
  2. 以不需要使用子查询的方式重写查询(我认为这并不总是可行)。
  3. 对于第二种选择,您的查询可能会变为:

    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:我没有测试过查询,因为我没有表格,但我经常使用这种方法。如果有任何拼写错误,请告诉我。

相关问题