这听起来很明显,但 Eloquent 不会在这里返回结果集,而是会返回一个集合。
如果您深入研究源代码(Builder::get
调用Builder::getFresh
、调用Builder::runSelect
、调用Connection::select
),您会发现其目的只是简单地返回结果,然后将结果放入集合(具有 sortBy 方法)中。
/**
* Run a select statement against the database.
*
* @param string $query
* @param array $bindings
* @param bool $useReadPdo
* @return array
*/
public function select($query, $bindings = array(), $useReadPdo = true)
{
return $this->run($query, $bindings, function($me, $query, $bindings) use ($useReadPdo)
{
if ($me->pretending()) return array();
// For select statements, we'll simply execute the query and return an array
// of the database result set. Each element in the array will be a single
// row from the database table, and will either be an array or objects.
$statement = $this->getPdoForSelect($useReadPdo)->prepare($query);
$statement->execute($me->prepareBindings($bindings));
//** this is a very basic form of fetching, it is limited to the PDO consts.
return $statement->fetchAll($me->getFetchMode());
});
}
如果您想在不加载每个项目的情况下进行分页,那么您需要使用@Marcin 的解决方案(复制如下):
$posts = Post::leftJoin('comments','posts.id','=','comments.post_id')->
selectRaw('posts.*, count(comments.post_id) AS `count`')->
groupBy('posts.id')->
orderBy('count','DESC')->
skip(0)->take(20)->get();