【问题标题】:Problem with fetching data from database in one to many polymorphic relations in Laravel在 Laravel 中以一对多多态关系从数据库中获取数据的问题
【发布时间】: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);}。

标签: php laravel


【解决方案1】:

选项 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

假设用户 hasMany 收藏记录 - hasMany 关系存在

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

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多