2017-08-09 64 views
0

我試圖找到條件的行,這是返回一個對象...關係法必須laravel雄辯

用戶有很多的個人資料照片,但有一個畫面是is_main

所以這是我寫的

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

public function active_picture() 
{ 
    return $this->profile_picture()->find($this->is_main); 
} 

現在,當我訪問它通過

$picture = Auth::user()->active_picture; 

它說

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation 

什麼是我必須做的,使其工作?

+0

我可能是錯的,但不是一對多關係假設使用'with'函數? https://laravel.com/docs/5.4/eloquent-relationships#eager-loading –

回答

0

你的代碼應該是

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

你缺少return語句

+0

對不起,這是一種類型。我忘了寫。 – Alen

+0

這不是解決方案....'Auth :: user() - > profile_picture'它的工作原理,但不是'Auth :: user() - > active_picture' – Alen

+0

對不起。你有沒有嘗試調用該訪問器,所以Auth :: user() - > active_picture(); –

0

我想你可以試試這個:

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

public function active_picture() 
{ 
    return $this->profile_picture()->find($this->is_main); 
} 

希望這對你的工作!

0

您必須使用

public function profile_picture() 
{ 
    return $this->hasMany(App\User_profile_picture::class); 
} 
0

如果你想使用一個模型方法作爲一個屬性,它返回一個關係。否則,您需要將其作爲()運算符的方法調用。像解釋here一樣。

所以解決你的問題應該是:

$picture = Auth::user()->active_picture(); 

編輯:直到你還可以設置自定義雄辯訪問:

public function getActivePictureAttribute() 
{ 
    return $this->profile_picture()->find($this->is_main); 
} 

$picture = Auth::user()->active_picture; 

是的,你必須寫得到...使用camelCase中的屬性,然後可以使用snake_case/kebab-case或camelCase中的屬性。 (請參閱雄辯的$ snakeAttributes布爾變量。)