2016-08-22 90 views
1

我渴望装载画廊这样这个得到错误而预先加载

$user = User::where('username', $username)->first(); 
     $favorites = Favorite::with('gallery')->where('user_id', $user->id)->get(); 
     dd($favorites->gallery); 

,并收到此错误信息:

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

我最喜欢的课是这样的:

class Favorite extends Model 
{ 
    protected $table = 'favorites'; 
    public function user(){ 
     return $this->belongsTo(User::class, 'user_id'); 
    } 
    public function gallery(){ 
     return $this->belongsTo(Gallery::class, 'gallery_id'); 
    } 
} 

但是,如果我这样做

$user = User::where('username', $username)->first(); 
     $favorites = Favorite::with('gallery')->where('user_id', $user->id)->get(); 
     dd($favorites); 

然后我得到这个image

回答

1

$favorites是一个集合,你不能得到一个集合的性质。

您需要使用first()从集合中获取第一个对象:

$favorites = Favorite::with('gallery')->where('user_id', $user->id)->first(); 

或者遍历集合并获取所有对象:

foreach ($favorites as $favorite) { 
    echo $favorite->gallery; 
}