我在想如何在雄辩中执行子查询。这里是包含我想要执行的子查询和我正在使用雄辩模型结构的数据库的要点。使用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();方法来执行原始查询或可能尝试使用加入,但我想坚持雄辩。任何类型的架构建议都会受到欢迎,因为我可能会错过一种可以使用雄辩的方式获得相同结果而不使用完全相同查询的方式。
在此先感谢。
我不认为这是可能的。没有办法。 – Gargron 2013-02-17 19:20:27
您将不得不创建自定义类方法并使用流畅的查询构建器。这不会是你想要的,但会做你需要的。查看[Fluent查询生成器](http://laravel.com/docs/database/fluent#aggregates) – Cristian 2013-02-18 17:18:56
另一个得到评论数的方法是'Post :: with('comments')'然后使用php在视图上使用'count()'方法。 – Cristian 2013-02-18 17:20:48