2017-03-08 90 views
0

我在我的模型类的一个这种关系:从雄辩的关系中返回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

作为一个方面的问题,我在做这个吧?这是做这件事的正确方法还是有更好的方法?

回答

1

我不确定!但是我认为可以使用count!当它返回0时,你知道没有记录,所以你可以返回null。

0

我不确定这是做到这一点的正确方法。在你的模型,你应该只定义你的关系:

public function userLike() 
{ 
    return $this->hasOne('App\Like'); 
} 

,然后在控制器或东西,你去拿喜欢你的用户是这样的:

class LikesController extends Controller { 

    public function getLike() 
    { 
     $like = null; 
     if (Auth::check()) { 
      $like = Like::where('user_id', Auth::user()->id)->first(); 
     } 
    } 
} 

因此,我们有getLike()功能得到类似于你的型号Like中的用户,其中user_id等于经过认证的用户的ID。

希望它有帮助!