Call to undefined method Illuminate\Database\Query\Builder::associate()

后端 未结 4 941
被撕碎了的回忆
被撕碎了的回忆 2021-01-01 11:29

Reference: How can I update an existing Eloquent relationship in Laravel 4?

$userinfo = \\Userinfo::find($id);
\\User::find($id)->userinfo()->associate         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 12:18

    associate() is a method of the belongsTo relationship, but it looks like from the above you are trying to call it via the hasOne relationship.

    I am just guessing as you have not provided your eloquent model class code so can't see how you have set the relationships exactly, but if you have:

    class User extends Eloquent {
        public function userinfo()
        {
            return $this->hasOne('Userinfo');
        }
    }
    
    class Userinfo extends Eloquent {
    
        public function user() {
            return $this->belongsTo('User');
        }
    }
    

    Then associate needs to be called against Userinfo as this has the belongsTo relationship to which the associate() method is attached.

    For example

    $user = \User::find(4);      
    $userinfo = \UserInfo::find(1);
    
    $userinfo->user()->associate($user);
    $userinfo->save();
    

    Will set the foreign key user_id in the user_info table to the id of the $user object.

    Looking at your above code it doesn't appear that this is what you are actually trying to do and that the

    $user->userinfo()->update($userinfoArray);
    

    call which you have commented out will in fact do what you seem to be trying to achieve, which is to update the userinfo that is related to the current user if that user already exists.

    Hope this helps.

    Glen

提交回复
热议问题