我在 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 表中获取与 favorites 表中的数据相对应的所有 profile_images。因此,profile_images 中的 id 匹配favoritable_id,user_profile_id 匹配user_id,favoritable_type 匹配favorites 表中的App\Models\ProfileImage。任何帮助表示赞赏。这是我的代码。
Controller
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模型之间没有关系,获取当前登录用户在favorites表中有条目的所有PostImage记录。
$profileImages = Favorite::where('user_id', auth()->id())
->with([
'favoritable' => fn($query) => $query->where('favoritable_type', ProfileImage::class)
])
->get()
->pluck('favoritable')
->flatten()
->all();
选项 2
假设用户有很多收藏记录 - 存在有很多关系
class User extends Model
{
public function favorites()
{
return $this->hasMany(Favorite::class);
}
// ...rest of the class code
}
通过用户模型获取结果
$profileImages = User::with([
'favorites' =>
fn($query) => $query->where('favoritable_type', ProfileImage::class)->with('favoritable')
])
->where('id', auth()->id())
->first()
->favorites
->pluck('favoritable')
->flatten()
->all();
关于php - Laravel 中以一对多多态关系从数据库获取数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65347832/