简体   繁体   中英

Problem with fetching data from database in one to many polymorphic relations in Laravel

I have one to many polymorphic relationship in Laravel and I am trying to fetch data using eloquent query. I have Favorite model with favorites table

id   user_id   favoritable_id   favoritable_type
1       17           1          App\Models\ProfileImage
2       10           1          App\Models\PostVideo   this is some other model

and profile_images table with

id   user_profile_id   title   path
1         17           etc      etc

I need to fetch all profile_images from profile_images table that correspond to data in favorites table. So id from profile_images to match favoritable_id, user_profile_id to matches user_id and favoritable_type to match App\Models\ProfileImage from favorites table. Any help is appreciated. Here is my code.

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;
}

Option 1

Assuming that there is no relation between User and Favorite models, get all the PostImage records which have an entry in favorites table for the currently logged in user.

$profileImages = Favorite::where('user_id', auth()->id())
    ->with([
        'favoritable' => fn($query) => $query->where('favoritable_type', ProfileImage::class)
    ])
    ->get()
    ->pluck('favoritable')
    ->flatten()
    ->all();

Option 2

Assuming that User hasMany Favorite records - hasMany relationship exists

class User extends Model
{
    public function favorites()
    {
        return $this->hasMany(Favorite::class);
    }

    // ...rest of the class code
}

Get the results via the User model

$profileImages = User::with([
    'favorites' => 
        fn($query) => $query->where('favoritable_type', ProfileImage::class)->with('favoritable')
    ])
    ->where('id', auth()->id())
    ->first()
    ->favorites
    ->pluck('favoritable')
    ->flatten()
    ->all();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM