如果能帮助我理解我在 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”时,就会进行查询。
我误解了“与”吗?
[为清楚起见,编辑以消除示例中的差异]
森林海