php - 在 Laravel 中以一对多多态关系从数据库中获取数据的问题
问题描述
我在 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;
}
解决方案
选项1
假设 User 和 Favorite 模型之间没有关系,获取当前登录用户在收藏夹表中有条目的所有 PostImage 记录。
$profileImages = Favorite::where('user_id', auth()->id())
->with([
'favoritable' => fn($query) => $query->where('favoritable_type', ProfileImage::class)
])
->get()
->pluck('favoritable')
->flatten()
->all();
选项 2
假设 User hasMany Favorite 记录 - hasMany 关系存在
class User extends Model
{
public function favorites()
{
return $this->hasMany(Favorite::class);
}
// ...rest of the class code
}
通过 User 模型获取结果
$profileImages = User::with([
'favorites' =>
fn($query) => $query->where('favoritable_type', ProfileImage::class)->with('favoritable')
])
->where('id', auth()->id())
->first()
->favorites
->pluck('favoritable')
->flatten()
->all();
推荐阅读
- c++ - Sysmalloc 断言在 C++ 中失败
- r - 如何在 R 中的地图中添加一列(基于圆圈的大小)?
- oracle - 用于赋值的 Oracle 游标
- javascript - 面临错误:-TypeError:无法读取 null 的属性“_id”
- python - 内部和外部匹配的正则表达式
- debian - 为单个用户自定义新的运行级别
- html - 如果光标位于 Azure 媒体播放器元素上,则无法滚动网页
- python - 有没有一种 Python 的方式来使用 with 语句来包装一个类?
- java - DB2JCC驱动jar调用不同jdk进行字符编码转换
- frontend - window.resizeTo : 当显示比例 > 100% 时弹出窗口的调整大小/比例有闪烁