通过Collection访问hasMany关系函数

 收藏

我正在尝试获取所有用户通知,并取决于用户是买家还是卖家(可以是两者)。我在通知表中做了两个功能,以相互过滤。 我的目标是最终运行:

$notifications = Auth::user()->notifications()->getBuyerNotifications();

要么

$notifications = Auth::user()->notifications()->getSellerNotifications();

I am running into an issue: Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany

用户模型:

public function notifications() {
   return $this->hasMany('App\Notification', 'user_id', 'id');
}

通知模型:

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

public static function getBuyerNotifications() {
  return self::whereNotNull('buyer_id')
              ->whereNull('deleted_at')
              ->get();

}

public static function getSellerNotifications() {
      return $this->whereNotNull('seller_id')
                    ->whereNull('deleted_at')
                    ->get();
}

The command I want to run to get all of the users notifications if they're a buyer: $notifications = Auth::user()->notifications()->getBuyerNotifications();

回复
  • yeum 回复

    Firstly, you don't need to use whereNull('deleted_at'), you can import the softDeletes Trait in your model:

    use Illuminate\Database\Eloquent\SoftDeletes;
    ...
    class Notification extends Model {
        use SoftDeletes;
        ...
    }
    

    Laravel will automatically use whereNull('deleted_at') on Eloquent-Builder.

    Secondly, you cannot use static method on Illuminate\Database\Eloquent\Relations\HasMany.

    Use scope method instead:

    public function scopeBuyerNotifications($query) {
        return $query->whereNotNull('buyer_id');
    }
    public function scopeSellerNotifications($query) {
        return $query->whereNotNull('seller_id');
    }
    

    因此,您可以找到这样的通知:

    $notifications = Auth::user()->notifications()->sellerNotifications()->get();
    
    $notifications = Auth::user()->notifications()->buyerNotifications()->get();