在我的模型中,我有:
//UserAddress.php
protected $with = ['address'];
public function address()
{
return $this->morphOne('App\Address', 'addressable');
}
//User.php
public function userAddress()
{
return $this->hasOne(UserAddress::class);
}
//Address.php
public function addressable()
{
return $this->morphTo();
}
但是当我打电话给dd(auth()->user()->userAddress))
时,地址真实性未加载。它仍然为空。
#attributes: array:4 [
"id" => "1"
"user_id" => "1"
"created_at" => "2018-11-13 10:11:54"
"updated_at" => "2018-11-13 10:11:54"
]
#original: array:4 [
"id" => "1"
"user_id" => "1"
"created_at" => "2018-11-13 10:11:54"
"updated_at" => "2018-11-13 10:11:54"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [
"address" => null
]
#touches: []
+timestamps: true
但是,对于dd(auth()->user()->userAddress()->get()))
,关系是渴望加载的。
出什么问题了?
修改
这太奇怪了。如果我写auth()->user()->userAddress->address
,我将得到null(不应该那样)。而当我移除protected $with = ['address'];
auth()->user()->userAddress->address
后,我便得到了正确的模型。
答案 0 :(得分:0)
我在ID字段是字符串的一对一关系中也遇到了同样的问题。一切正常,直到我急于加载连接表(您的情况下为user_address)。
在我的情况下,我忘记了在连接表中定义public $incrementing = false;
,并且一旦添加了它,一切都会起作用。