如何select模型中eloquent关系中的特定列?
How to select specific column in eloquent relationship inside the Model?
已编辑: 伙计们,你能看看你推荐的副本吗?在我问这个问题之前我做了一些研究,我已经 link,这不是我正在寻找的答案。
如何提取 eloquent 关系中的特定列?当我 Student::find()->subject;
时,我只想返回 name
列
我尝试了以下代码,但没有用,returns 我出错了
App\Student::subject must return a relationship instance.
class Student extends Model
{
protected $table = 'subjects';
protected $fillables = ['id', 'name', 'gender', 'birthdate', etc.];
public function subject()
{
return $this->hasMany('App\Subject')->pluck('name');
}
}
您可以对关系使用任何查询构建器函数。
使用 select
仅 select 名称列
public function subject()
{
return $this->hasMany('App\Subject')->select('name');
}
已编辑: 伙计们,你能看看你推荐的副本吗?在我问这个问题之前我做了一些研究,我已经 link,这不是我正在寻找的答案。
如何提取 eloquent 关系中的特定列?当我
Student::find()->subject;
时,我只想返回 name
列
我尝试了以下代码,但没有用,returns 我出错了
App\Student::subject must return a relationship instance.
class Student extends Model
{
protected $table = 'subjects';
protected $fillables = ['id', 'name', 'gender', 'birthdate', etc.];
public function subject()
{
return $this->hasMany('App\Subject')->pluck('name');
}
}
您可以对关系使用任何查询构建器函数。
使用 select
仅 select 名称列
public function subject()
{
return $this->hasMany('App\Subject')->select('name');
}