我正在尝试获取选定的列而不是完整的列。
$profiles= auth()->user()->profile()->where('id', $id)->select('profile.id','profile.name');
和我的 profile()
方法
public function profile()
{
return $this->hasMany(Profile::class)->get();
}
如果我删除 ->select('profile.id','profile.name')
,它会返回 profile
表的完整列,但我只想要它的几列。如果我添加 ->select()
它会给我以下错误:
BadMethodCallException: 方法 Illuminate\Database\Eloquent\Collection::select 不存在。在文件中
请建议更改方法调用。谢谢。
get()
在 select()
之前调用(在 profile()
中)这是错误的,因为您试图在获取的 select()
上调用 Collection
方法。因此,请从您的关系函数中删除 get()
。
public function profile()
{
return $this->hasMany(Profile::class);
}
注意:如果在 user()
中使用 get()
,请执行相同的操作。
您可以尝试将 ->select('profile.id','profile.name')
更改为 ->pluck('profile.id','profile.name')
吗?