【问题标题】:Select column from relations relation in laravel从laravel中的关系关系中选择列
【发布时间】:2018-09-16 11:12:10
【问题描述】:

我正在尝试使用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();
}

其他与文章模型有多态关系的模型

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

【问题讨论】:

  • 请也添加您的迁移和模型,这会有所帮助
  • 我前段时间也遇到过同样的问题,貌似是因为复杂,morph关系对select语句无所谓。看这里:github.com/laravel/framework/issues/2966
  • @FatemehMajd 四年过去了,仍然不支持:/
  • 因为不是技术问题,是有morph关系的时候,select column没有意义。每个变形模型上可能有不同的列
  • @FatemehMajd 所有变形模型都有一些名称与标题相同的 clumns

标签: laravel laravel-5 eloquent polymorphic-associations


【解决方案1】:

这已在 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();

【讨论】:

  • 我应该检查新的提交 .. :/
猜你喜欢
  • 2021-12-24
  • 2013-04-03
  • 1970-01-01
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2011-09-24
相关资源
最近更新 更多