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.

    评论

报告相同问题?