【发布时间】:2020-12-18 16:47:35
【问题描述】:
我在 Laravel 中有一对多的多态关系,我正在尝试使用 eloquent 查询来获取数据。我有收藏夹表的收藏模型
id user_id favoritable_id favoritable_type
1 17 1 App\Models\ProfileImage
2 10 1 App\Models\PostVideo this is some other model
和 profile_images 表与
id user_profile_id title path
1 17 etc etc
我需要从 profile_images 表中获取与收藏夹表中的数据相对应的所有 profile_images。因此,profile_images 中的 id 与 favouritable_id 匹配,user_profile_id 与 user_id 匹配,并且 favouritable_type 与收藏夹表中的 App\Models\ProfileImage 匹配。任何帮助表示赞赏。这是我的代码。
控制器
public function getProfileImages()
{
$profileimage = ProfileImage::whereColumn('id', 'favoritable_id')->first();
// I AM BASICALLY STUCK HERE WITH $profileimage !!!
$favoriteProfileImages = $profileimage->favorites()->where([
'user_id' => auth()->id(),
'favoritable_id' => $profileimage->id,
'favoritable_type' => ProfileImage::class
])->get();
return $favoriteProfileImages;
}
【问题讨论】:
-
不太明白你想要什么。您是否想获取已收藏的 ProfileImage 的所有记录,即收藏表中有记录。或者您想从收藏夹表中获取与当前登录用户关联的所有记录
-
@Donkarnash 我想要在当前登录用户的收藏夹表中有条目的个人资料图片
-
用户和收藏夹之间是什么关系 - 如果有的话?
-
@Donkarnash 在收藏夹模型中,我在收藏夹表中有带有 user_id 的公共函数 user(){return $this->belongsTo(User::class);}。