【问题标题】:Laravel: hasMany relationship + where condition failsLaravel:hasMany关系+条件失败
【发布时间】: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()-&gt;user()-&gt;is 就是NULL,我得到:

ErrorException {#1483 #message: "试图获取属性 'id' 非对象”

问题:如何在wishLists() 中引用user_id 值?

WishList 模型有这个:

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id');
}

那么我可以使用$this-&gt;user-&gt;id 之类的东西吗?

编辑:

不,这也行不通。

【问题讨论】:

    标签: mysql laravel laravel-5 eloquent


    【解决方案1】:

    您必须检查用户是否已登录?

    Auth::check() ? Auth::user()->id : null
    

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      相关资源
      最近更新 更多