【发布时间】:2020-03-27 05:01:45
【问题描述】:
我正在尝试获取所有用户通知,具体取决于用户是买家还是卖家(可以同时是两者)。我在通知表中创建了两个函数来相互过滤。 我的目标是最终运行:
$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();
【问题讨论】:
-
为什么是那些静态方法?
-
@jeremykenedy 正在测试一些东西 - 不需要它是静态的
-
只是好奇,当您只有
$notifications = Auth::user()->notifications时会发生错误吗? -
@jeremykenedy 没有错误。只返回一个通知集合
-
@jeremykenedy 现在我可以在一行中执行 notification()->whereNotNull('buyer_id') 等,但将它放在一个函数中将是理想的,因此任何人都可以调用它
标签: php laravel laravel-5 laravel-7