簡體   English   中英

如何在 Laravel 中獲取嵌套關系的實例?

[英]How to get instance of nested relationship in Laravel?

我有User模型,有很多 morph 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","exception":"[object] (BadMethodCallException(代碼:0):調用未定義的方法 Illuminate\\Database\\Eloquent\\Relations\\MorphMany::notification_type()`

是否可以直接從$user獲取 notification_type ?

提前致謝!

實際上,我剛剛找到了解決方案。 由於$user->notifications()Illuminate\\Database\\Eloquent\\Relations\\MorphMany的實例,所以有一個函數可以獲取Notification模型的實例,即getRelated() 我在這里找到

既然拿到了Notification模型類,我終於可以檢索到notification_type()關系方法了。

這是我的固定代碼:

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

我願意接受任何改進或修復上述代碼的建議。 謝謝你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM