通过 Collection 访问 hasMany 关系函数

Accessing a hasMany relation function via Collection

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

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

首先,你不需要使用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();

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;

您可以在用户模型中添加另外两个方法,如下所示

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