【问题标题】:how display for unlogged user output of a relation which haswhere clasue with logged user ID如何显示具有 where 子句和已记录用户 ID 的关系的未记录用户输出
【发布时间】:2015-03-07 18:40:06
【问题描述】:

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

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())

它有效,但它看起来不是一个好习惯。

选项 2: 代替

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

我会放

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

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


【问题讨论】:

    标签: php authentication laravel model eloquent


    【解决方案1】:

    我会选择选项 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');
    

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 2023-04-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      相关资源
      最近更新 更多