【问题标题】:Relationship method must return an object in laravel eloquent关系方法必须在 laravel eloquent 中返回一个对象
【发布时间】:2018-01-17 04:34:06
【问题描述】:

我正在尝试查找有条件的行,那就是...

一个用户有很多个人资料图片,但只有一张图片是is_main

这就是我写的

public function profile_picture()
{
    return $this->hasMany('App\User_profile_picture');
}

public function active_picture()
{
    return $this->profile_picture()->find($this->is_main);
}

现在当我通过

访问它时
$picture = Auth::user()->active_picture;

上面写着

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

我必须做些什么才能让它发挥作用?

【问题讨论】:

标签: php laravel laravel-5 eloquent laravel-5.3


【解决方案1】:

你的代码应该是

public function profile_picture()
{
    return $this->hasMany('App\User_profile_picture');
}

您缺少返回语句

【讨论】:

  • 对不起,这是一种类型。我忘记写了。
  • 这不是解决方案.... Auth::user()->profile_picture 有效但无效 Auth::user()->active_picture
  • 对不起。您是否尝试过调用该访问器,所以 Auth::user()->active_picture();
【解决方案2】:

我想你可以试试这个:

public function profile_picture()
{
    return $this->hasMany('App\User_profile_picture');
}

public function active_picture()
{
    return $this->profile_picture()->find($this->is_main);
}

希望这对你有用!!!

【讨论】:

    【解决方案3】:

    你必须使用class

    public function profile_picture()
    {
       return $this->hasMany(App\User_profile_picture::class);
    }
    

    【讨论】:

      【解决方案4】:

      如果你想使用一个模型方法作为一个属性,它必须返回一个关系。否则,您需要使用 () 运算符将其作为方法调用。就像解释here

      所以你的问题的解决方案是:

      $picture = Auth::user()->active_picture();
      

      编辑:TIL 你也可以设置一个自定义的 eloquent 访问器:

      public function getActivePictureAttribute()
      {
          return $this->profile_picture()->find($this->is_main);
      }
      
      $picture = Auth::user()->active_picture;
      

      是的,你必须在camelCase中编写get...Attribute,然后才能使用snake_case/kebab-case或camelCase中的属性。 (参见雄辩的 $snakeAttributes 布尔变量。)

      【讨论】:

        猜你喜欢
        • 2018-03-20
        • 2014-07-09
        • 2015-11-05
        • 2017-05-16
        • 1970-01-01
        • 2014-06-26
        • 1970-01-01
        • 2017-12-21
        相关资源
        最近更新 更多