Search code examples
laravellaravel-5eloquentpolymorphic-associations

Select column from relations relation in laravel


I'm trying to do eager loading using with() method, I only want to get selected column from relations relation, how can I do that ? . I'm using polymorphic relation.

Draft::with(["user:id,username","article:id,locale","article.articleable:title"])->where([
            ["user_id",$user_id],
            ["is_suspended",1]
        ])->get();

Draft Model

public function article()
{
    return $this->belongsTo("App\Models\Article");
}

Article Model

public function drafts()
{
    return $this->hasMany("App\Models\Draft", "article_id", "id");
}

public function articleable()
{
    return $this->morphTo();
}

other models which has polymorphic relation with Article model

public function articles()
{
    return $this->morphMany("App\Models\Article", "articleable");
}

Solution

  • This has been fixed in Laravel 5.7.6: https://github.com/laravel/framework/pull/25662

    In order for this to work, you also have to select the id column:

    Draft::with('user:id,username', 'article:id,locale', 'article.articleable:id,title')
                                                                              ^^
        ->where([
            ['user_id', $user_id],
            ['is_suspended', 1]
        ])->get();