doushao8421 2018-02-14 07:42
浏览 81

被认为是OneToMany关系中定义的外键的存取器

My User model have these fields :

user_id
username
name
family
supervisor

And in that model I defined an accesssor that same name as supervisor attribute like this (because I want to return supervisor user as an User object and not a simple id):

public function getSupervisorAttribute($value)
{
    return is_null($value) ? null : User::select('user_id', 'name', 'family')->find($value);
}

In the other hand there is a OneToMany relationship like this:

public function child()
{
    return $this->hasMany(self::class, 'supervisor', 'user_id');
}

Now each time I call child() relation it return Illegal offset type error. seems that supervisor field does not recognized in second argument of hasMany method.

There is any way to solve this problem Without having to change accessor name.

  • 写回答

2条回答 默认 最新

  • douzou7012 2018-02-14 08:43
    关注

    I think the problem comes when you try to retrieve the relationship child, why? Because you have an accessor on your supervisor which is a foreign key inside of child relationship, so what happens is when you ask for that relationship, Laravel will try to use your supervisor property, since it has an accessor, it will trigger and instead of getting a desired property (which i guess is an integer), you will either get NULL or a User. I hope this clarifies it for you.

    One workaround for this is to add appends attribute to your Model and then put mutators and accessors on that attribute.

    评论

报告相同问题?

悬赏问题

  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件
  • ¥15 关于用pyqt6的项目开发该怎么把前段后端和业务层分离
  • ¥30 线性代数的问题,我真的忘了线代的知识了
  • ¥15 有谁能够把华为matebook e 高通骁龙850刷成安卓系统,或者安装安卓系统
  • ¥188 需要修改一个工具,懂得汇编的人来。
  • ¥15 livecharts wpf piechart 属性
  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了