通过集合访问hasMany关系函数

时间:2020-03-27 05:01:45

标签: php laravel laravel-5 laravel-7

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

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

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

我遇到了一个问题: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();
}

我想运行的命令来获取所有用户的购买通知:$notifications = Auth::user()->notifications()->getBuyerNotifications();

3 个答案:

答案 0 :(得分:0)

首先,您无需使用whereNull('deleted_at'),可以在模型中导入softDeletes特性:

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

Laravel将在Eloquent-Builder上自动使用whereNull('deleted_at')

第二,您不能在Illuminate\Database\Eloquent\Relations\HasMany上使用静态方法。

改为使用scope方法:

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();

答案 1 :(得分:0)

Auth::user()使用会话数据。

尝试一下:

optional(User::find(Auth::id())->notifications)->getBuyerNotifications;

$userId = 1; // Example id you can just pass the user Id.
User::find($userId)->notifications->getBuyerNotifications;

答案 2 :(得分:0)

您可以在用户模型中添加以下两种其他方法

public function getBuyerNotifications() {
    return $this->hasMany('App\Notification', 'buyer_id', 'id');
}
public function getSellerNotifications() {
    return $this->hasMany('App\Notification', 'seller_id', 'id');
}

您可以直接从用户实例中调用它

$user->getBuyerNotifications();
$user->getSellerNotifications();