[英]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.