Laravel 预加载仅在调用属性时有效
Laravel Eager-loading works only when calling attribute
我已经定义了我的 Slot 模型来加载来自 User 模型的关系,如下所示:
public function userAssignedFull(): HasOne {
return $this->hasOne(User::class,'id','user_assigned');
}
('slots' table 包含 'user_assigned' 字段,我通过该字段连接到 'id' 上的用户记录)
以下代码找到插槽模型但没有 'userAssignedFull'。我只得到 'user_assigned'.
中的用户 ID
$slot = Slot::with('userAssignedFull')->find($slot_id);
但后来称这个为 returns 我想要的关系:
$fullUserModel = $slot->userAssignedFull;
谁能告诉我我做错了什么?
Builder::with()
returns the Builder 个实例。
所以你必须调用$slot->userAssignedFull;
来获取数据集合。
来自docs:
When accessing Eloquent relationships as properties, the relationship
data is "lazy loaded". This means the relationship data is not
actually loaded until you first access the property.
而这个$slot->userAssignedFull;
就是你的"first access the property".
试试这个
$slot = Slot::where('id', $slot_id)->with('userAssignedFull')->first();
$slot->userAssignedFull;
我已经定义了我的 Slot 模型来加载来自 User 模型的关系,如下所示:
public function userAssignedFull(): HasOne {
return $this->hasOne(User::class,'id','user_assigned');
}
('slots' table 包含 'user_assigned' 字段,我通过该字段连接到 'id' 上的用户记录)
以下代码找到插槽模型但没有 'userAssignedFull'。我只得到 'user_assigned'.
中的用户 ID $slot = Slot::with('userAssignedFull')->find($slot_id);
但后来称这个为 returns 我想要的关系:
$fullUserModel = $slot->userAssignedFull;
谁能告诉我我做错了什么?
Builder::with()
returns the Builder 个实例。
所以你必须调用$slot->userAssignedFull;
来获取数据集合。
来自docs:
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property.
而这个$slot->userAssignedFull;
就是你的"first access the property".
试试这个
$slot = Slot::where('id', $slot_id)->with('userAssignedFull')->first();
$slot->userAssignedFull;