php - Laravel 中以一对多多态关系从数据库获取数据的问题

标签 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 表中获取与 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/

相关文章:

php - MYSQL 列中有 9,000 个字符串 - 使用哪种数据类型?

php - 使用Direct-Upload上传到Youtube后无法获取视频ID

php - 新日期时间 ('2016-04-01 00:00:00' ) 返回 '2016-04-01 12 :00:00

Laravel 通过 Jwt token 获取用户信息

php - 替换php字符串的某些部分

php - 准备好的语句: num_rows is always zero

php - DateTime::__construct(): 无法解析位置 20 处的时间字符串 (2022 年 5 月 5 日 12:00:00:AM) (:):意外字符

php - AWS EC2 上的 Laravel 开发

laravel - 警告 : require(/var/www/vendor/autoload. php):

facebook-php-sdk - 我的 Laravel 应用无法在 Facebook 上运行