nicklaw5's avatar

How to return select('column, titles') with eager loading and pagination?

I have realised that it is not possible to do eager loading with a select statement after reading this post. My question is: how am i able to select only certain columns alongside eager loading and pagination. See my current code below as an example?

class ForumThread extends Model
{
    /**
     * Get the user that owns the thread.
     */
    public function owner()
    {
        return $this->belongsTo('App\Models\User', 'created_by');
    }

    /**
     * Get the forum category that owns the thread.
     */
    public function category()
    {
        return $this->belongsTo('App\Models\ForumCategory', 'forum_category_id');
    }

    /**
     * Get the replies for this thread.
     */
    public function replies()
    {
        return $this->hasMany('App\Models\ForumReply');
    }

    /**
     * 
     * @return obj
     */
    public function getCategoryThreads($category)
    {
        $threads = 
            $this->select(
                DB::raw('forum_threads.id AS thread_id, forum_threads.uuid AS thread_uuid,
                         forum_threads.title, forum_threads.thread_slug, forum_threads.is_sticky,
                         forum_threads.is_locked, forum_threads.likes, forum_threads.views,
                         forum_threads.created_by, forum_threads.created_at, u.uuid as user_uuid,
                         u.username, u.display_name, u.avatar'))
            ->join('users AS u', 'forum_threads.created_by', '=', 'u.id')
            ->with(['category', 'replies']) // these are not being returned
            ->where('forum_category_id', $category->id)
            ->where('is_published', 1)
            ->orderBy('is_sticky', 'desc')
            ->orderBy('forum_threads.created_at', 'desc')
            ->paginate(10);

        return $threads;
    }
}
0 likes
2 replies
jekinney's avatar

First is you're query is query builder not eloquent and you're trying to use eloquent methods.

nicklaw5's avatar

Yes @jekinney I am aware of that. I acknowledged this in the first sentence of my question.

Please or to participate in this conversation.