如何显示具有 where 子句和已登录用户 ID 的关系的未登录用户输出

how display for unlogged user output of a relation which haswhere clasue with logged user ID

我有这个关系,其中包含对登录用户的引用

public function booksdislikedbyUser()
{
return $this->hasMany('Userattitude')->where('creator_id', Auth::user()->id)->selectRaw('count(IF(attitude = -1,0,1)) as dislikedbooks')->groupBy('entity_id');

}

显示输出的我的 VIEW 文件必须对已登录和未登录的用户可见。

问题:如果用户未登录,我会收到此错误: 尝试获取 属性 的非对象

我的问题:如果我想获取视图并禁用(?)关系,最佳做法是什么?

选项 1: 我要做的是将代码的两个变体放在 IF - ELSE 括号中。

if(Auth::check())

有效,但 doesn.t 看起来是个好习惯。

选项 2: 代替

->where('creator_id', Auth::user())

我会放

->where('creator_id', ($user_id ? $user_id : NULL))

那我应该在哪里定义变量呢? $user_id = Auth::user()->id;


我会选择选项 2。

public function booksdislikedbyUser()
{
    $userId = (Auth::user() ? Auth::user()->id : null);
    return $this->hasMany('Userattitude')->where('creator_id', $userId)->selectRaw('count(IF(attitude = -1,0,1)) as dislikedbooks')->groupBy('entity_id');
}

或者更简单,使用Auth::id()函数:

return $this->hasMany('Userattitude')->where('creator_id', Auth::id())->selectRaw('count(IF(attitude = -1,0,1)) as dislikedbooks')->groupBy('entity_id');