【发布时间】:2019-02-08 00:13:50
【问题描述】:
我有一个Customer Eloquent 模型。 Customer 可以有多个WishLists,他/她可以在其中添加一些产品。典型的电子商务功能。
重点是Customer 可以属于许多Users 模型。
这很简单:
public function users()
{
return $this->belongsToMany(User::class, 'users_sync_customers', 'customer_uuid', 'user_id')
->withTimestamps()
->orderBy('last_name', 'asc');
}
所以我可以得到所有分配给登录用户的Customers
auth()->user()->customers????
正如我提到的,Customer 可以有多个Wishlists:
public function wishLists()
{
return $this
->hasMany(WishList::class, 'customer_uuid', 'uuid')
->where('user_id', '=', auth()->user()->id); // <----- this will fail when I log out
}
但WishList 的范围为客户 UUID 和用户 ID。
以上关系有效,但仅当我明显登录时。
我一注销,auth()->user()->is 就是NULL,我得到:
ErrorException {#1483 #message: "试图获取属性 'id' 非对象”
问题:如何在wishLists() 中引用user_id 值?
WishList 模型有这个:
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
那么我可以使用$this->user->id 之类的东西吗?
编辑:
不,这也行不通。
【问题讨论】:
标签: mysql laravel laravel-5 eloquent