【发布时间】:2021-09-07 18:19:40
【问题描述】:
我有User 模型,
有很多变形Notification。 Notification 模型也属于一个 NotificationType。我想通过User 实例从NotificationType 中查找数据。这是关系代码:
// User.php
public function notifications()
{
return $this->morphMany(Notification::class, 'notifiable');
}
// Notification.php
public function notification_type()
{
return $this->belongsTo(NotificationType::class, 'notification_type_id');
}
这是我尝试过的代码:
$notificationType = $user->notifications()->notification_type()->where('name', $this->data->type)->first();
但是,它会返回
staging.ERROR:调用未定义的方法 Illuminate\Database\Eloquent\Relations\MorphMany::notification_type() {"userId":"996cdaea-c6f3-444a-a430-036e1966ab91","异常":"[对象] (BadMethodCallException(代码:0):调用未定义的方法 Illuminate\Database\Eloquent\Relations\MorphMany::notification_type()`
是否可以直接从$user获取notification_type?
提前致谢!
【问题讨论】:
-
感谢您的评论。我已经尝试了你所有的建议,但它们似乎没有奏效。对于第一个,它将在 users 表上执行 where(),而不是 notification_types 表。第二个,它抛出一个错误,因为用户模型没有 notification_type() 方法。
-
感谢您帮助我,但抱歉,我认为您误解了我的问题。我想获取 notification_type 数据,而不是用户数据。