Laravel sortBy paginate

前端 未结 3 703
太阳男子
太阳男子 2021-01-06 00:14

I have a posts table and comments table, comment belongs to post, and I have the relationship setup in Post and Comment model. I did sort posts by the numb

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 00:38

    This sounds obvious, but Eloquent will not return a result set here, but rather it will return a collection.

    If you dig into the source (Builder::get calls Builder::getFresh, which calls Builder::runSelect, which calls Connection::select), you'll find that it's intention is to simply return the results, which are then placed into a collection (which has the sortBy method).

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

    If you want to have pagination without loading every item, then you need to use @Marcin's solution (duplicated below):

    $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();
    

提交回复
热议问题