我在我的模型类的一个这种关系:从雄辩的关系中返回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
作为一个方面的问题,我在做这个吧?这是做这件事的正确方法还是有更好的方法?