如果能帮助我理解我在 laravel 6.8 项目中看到的以下差异,我将不胜感激:我有一个“UserAlert”模型class UserAlert extends Model{ /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'user_id', 'from_id', 'subject', 'message' ]; //Relationships public function user() { return $this->belongsTo(User::class); } //Only include the name of the sender in this relationship public function from() { return $this->hasOne(User::class, 'id', 'from_id')->select('name'); }}“用户”关系是默认的“user_id”到“id”,并且按预期工作。如您所见,“来自”关系从与 UserAlert 的“from_id”关联的用户模型中提取名称。如果我获得 UserAlerts 的集合,然后对其进行迭代以获取每个 UserAlerts 的“来源”关系,如下所示:$thisUserAlerts = \App\UserAlert::where('user_id', $thisUser->id)->get();foreach ($thisUserAlerts as $userAlert) { dump($userAlert->from);}然后我确实按照我的意愿从“来自”关系中看到了名字:...#original: array:1 [ "name" => "Administrator" ]...但是,如果我尝试使用“with”将关系直接包含在 UserAlert 集合中,则“from”始终为空。$thisUserAlertsWith = \App\UserAlert::where('user_id', $thisUser->id)->with('from')->get();dump($thisUserAlertsWith);...#relations: array:1 [ "from" => null ]...我可以从查询日志中看到,当我执行上述操作时,没有从用户表中提取名称的 sql 查询,但是当我遍历集合并直接调用“->from”时,就会进行查询。我误解了“与”吗?[为清楚起见,编辑以消除示例中的差异]
1 回答

森林海
TA贡献2011条经验 获得超2个赞
对于要包含的关系,事实证明您必须在集合中包含主键 (id)。
所以第一个答案是修改关系
return $this->hasOne(User::class, 'id', 'from_id')->select('name');
到
return $this->hasOne(User::class, 'id', 'from_id')->select(['id', 'name']);
然后我的原始示例按预期工作。
对此进行研究也让我想到了另一种选择,即不限制关系本身的字段,而是在“with”调用中限制它们。
所以从关系中完全删除选择:
return $this->hasOne(User::class, 'id', 'from_id')
而是使用以下内容过滤集合:
$userAlerts = UserAlert::where('user_id', $id)->with('from:id,name')->get();
同样,您必须包含主键 (id) 才能正常工作。
- 1 回答
- 0 关注
- 126 浏览
添加回答
举报
0/150
提交
取消