用户关注问题的多对多关联,查询不到数据的时候报错:
User.php
//用户关注问题,users表与quesitons表多对多关联
public function follows ()
{
return $this->belongsToMany('App\Quesiton','user_question')->withTimestamps();
}
//返回用户是否关注了某个问题
public function followed($question)
{
return $this->follows()->where('question_id', $question)->count();
}
welcome.blade.php
//在视图中显示用户是否关注了问题,
{{ Auth::user()->followed($question->id) ? '已关注':'关注' }}
当用户没有关注问题的时候,报错:
Call to a member function followed() on null
可是用dd()又能返回0或1:
TestController.php
public function isFollowedOrNot($question)
{
dd(Auth::user()->followed($question)); //0
}
解决方案:
在 {{ Auth::user()->followed($question->id) ? ‘已关注’:’关注’ }} 这个用的时候,Auth::user() 是 null, 这个问题出现应该是在用户没有登录的时候发生的。我们可以用Auth::check() 判断吧。
达维营-前端网