2017-03-08 93 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。

希望它有幫助!