我在我的模型類的一個這種關係:從雄辯的關係中返回null?
public function userLike()
{
if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);
// RETURN NULL IF RECORD DOESN'T EXIST?
}
正如你所看到的,它會檢查用戶登錄並返回Like
記錄。但是,如果記錄不存在,我該如何返回null?
我嘗試這樣做:
public function userLike()
{
if (Auth::check()) return $this->hasOne('App\Like')->where('user_id', Auth::user()->id);
return null;
}
但我得到的錯誤:
local.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to a member function addEagerConstraints() on null' in /var/www/social/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:680
作爲一個方面的問題,我在做這個吧?這是做這件事的正確方法還是有更好的方法?