Laravel Eloquent - 集合中的父项列表

Laravel Eloquent - list of parent from a collection

我可以从商店 1 中获取用户 1 在媒体上点赞的列表

$medias = User::find(1)->likes()->with('media')->whereHas('media', function($q) {
    $q->where('store_id', '=', 1);
})->get();

但是我需要检索媒体列表,所以我尝试了

$medias = User::find(1)->likes()->with('media')->whereHas('media', function($q) {
    $q->where('store_id', '=', 1);
})->get()->media;

但后来我得到

Undefined property: Illuminate\Database\Eloquent\Collection::$media

class User extends Model
{
    public function likes()
    {
        return $this->hasMany('App\Like');
    }
}

class Media extends Model
{
    public function store()
    {
        return $this->belongsTo('App\Store');
    }

    public function likes()
    {
        return $this->hasMany('App\Like');
    }
}

class Like extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function media()
    {
        return $this->belongsTo('App\Media');
    }
}

这是因为您会为每个点赞获取单独的媒体。你应该使用:

$likes = User::find(1)->likes()->with('media')->whereHas('media', function($q) {
    $q->where('store_id', '=', 1);
})->get();

foreach ($likes as $like) {
   $media = $like->media;
   // now you can do something with your media
}

编辑

如果您只想获取媒体,您应该将以下关系添加到您的 User 模型中:

public function medias()
{
    return $this->hasManyThrough('App\Media','App\Like');
}

现在要获取媒体,您应该这样做:

$medias = User::find(1)->medias()->where('store_id', '=', 1)->get();

使其适用于

$store->medias()->whereHas('likes', function($q) use($user) {
        return $q->where('user_id', '=', $user->id);
    });