用户关注问题的多对多关联,查询不到数据的时候报错:
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()
判断吧。