我正在尝试获取所有用户的通知,具体取决于用户是买家还是卖家(两者都可以(。我在我的通知表中创建了两个函数来过滤彼此。我的目标是最终运行:
$notifications = Auth::user()->notifications()->getBuyerNotifications();
或
$notifications = Auth::user()->notifications()->getSellerNotifications();
我遇到了一个问题:Call to undefined method IlluminateDatabaseEloquentRelationsHasMany
用户模型:
public function notifications() {
return $this->hasMany('AppNotification', 'user_id', 'id');
}
通知模型:
public function user() {
return $this->belongsTo('AppUser', '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 Trait:
use IlluminateDatabaseEloquentSoftDeletes;
...
class Notification extends Model {
use SoftDeletes;
...
}
Laravel将在Eloquent Builder上自动使用whereNull('deleted_at')
。
其次,不能在IlluminateDatabaseEloquentRelationsHasMany
上使用静态方法。
改为使用范围方法:
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('AppNotification', 'buyer_id', 'id');
}
public function getSellerNotifications() {
return $this->hasMany('AppNotification', 'seller_id', 'id');
}
您可以直接从用户实例调用它
$user->getBuyerNotifications();
$user->getSellerNotifications();