2016-08-22 39 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; 
}