Sembra ovvio, ma Eloquent non restituirà un risultato impostato qui, ma restituirà una raccolta.
Se si scava nella fonte (Builder::get
chiamate Builder::getFresh
, che chiama Builder::runSelect
, che chiama Connection::select
), troverete che è intenzione è di tornare semplicemente i risultati, che vengono poi inseriti in una collezione (che ha la SortBy metodo).
/**
* 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());
});
}
Se si desidera avere la paginazione senza caricare ogni elemento, allora avete bisogno di usare @ la soluzione di Marcin (duplicato sotto):
$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();
Thansk, così tanto per essere chiari, questa soluzione non sarà recupera tutti i record dal database e poi li risolve, recupera solo 20 record all'inizio, giusto? – dulan
@dulan, sì, se stiamo parlando del 2 ° codice. Nel primo codice tutti i record verranno recuperati dal database e visualizzati solo alcuni di essi, quindi è necessario scegliere la seconda soluzione –
grazie per l'utilizzo di skip() –