首页 > 解决方案 > 在 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;
}

标签: phplaravel

解决方案


选项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();

推荐阅读