首页 > 解决方案 > 从laravel中的关系关系中选择列

问题描述

我正在尝试使用with()方法进行预加载,我只想从关系关系中获取选定的列,我该怎么做?. 我正在使用多态关系。

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

模型草稿

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

文章模型

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

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

与 Article 模型具有多态关系的其他模型

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

标签: laravellaravel-5eloquentpolymorphic-associations

解决方案


这已在 Laravel 5.7.6 中修复:https ://github.com/laravel/framework/pull/25662

为了使其工作,您还必须选择id列:

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

推荐阅读