【发布时间】:2021-05-27 13:40:12
【问题描述】:
我正在尝试获取选定的列而不是完整的列。
$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 不存在。在文件中
请建议更改方法调用。谢谢。
【问题讨论】:
-
收集助手laravel.com/docs/8.x/collections没有这种方法可以使用
-
这就是你没有把
->get()放在hasMany()之后的原因;您完全删除了链接查询的能力,例如select()、where()等,因为您正在立即执行查询。仔细检查文档laravel.com/docs/8.x/eloquent-relationships,在hasOne()、hasMany()、belongsTo()等之后,没有一个示例函数使用->get()或->first(),现在你知道为什么了:)