【问题标题】:How to get instance of nested relationship in Laravel?如何在 Laravel 中获取嵌套关系的实例?
【发布时间】:2021-09-07 18:19:40
【问题描述】:

我有User 模型, 有很多变形NotificationNotification 模型也属于一个 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 数据,而不是用户数据。

标签: php laravel eloquent


【解决方案1】:

其实,我刚刚找到了解决方案。由于$user->notifications()Illuminate\Database\Eloquent\Relations\MorphMany的实例,所以有一个函数可以获取Notification模型的实例,即getRelated()。我找到了here

自从我得到Notification模型类,我终于可以检索notification_type()关系方法了。

这是我的固定代码:

$notificationType = $user->notifications()->getRelated()->notification_type()->getRelated()->where('name', $this->data['type'])->first();

我愿意接受任何改进或修复上述代码的建议。谢谢。

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 2016-09-26
    • 2022-11-23
    • 2020-04-04
    • 2020-12-06
    • 2019-11-17
    • 2021-08-25
    • 2021-01-24
    相关资源
    最近更新 更多