我可以获取用户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;
然后我得到了
未定义的属性: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');
}
}
答案 0 :(得分:0)
这是因为你为每个媒体分开了媒体。你应该使用:
$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();
答案 1 :(得分:0)
使用
theString