Tuesday, April 4, 2017

Polymorphic relation - morphTo save() not recognizing custom primary key

User model:

public function userable()
{
    return $this->morphTo();
}

Mentor model:

public function user()
{
    return $this->morphOne('App\Models\User', 'userable');
}

The student model looks the same as the mentor model.

The tables for Students and Mentors contain a custom PK called user_id which references the primary key on the users table.

So what I'm trying to do is the following:

    $user = new User();
    $user->first_name = 'Trajce';
    $user->last_name = 'Petkoski';
    $user->nickname = 'ads';
    $user->administrator = '0';
    $user->email = 'asd';
    $user->password = Hash::make('test');
    $user->save();

    $mentor = new Mentor();
    $mentor->user_id = $user->id;
    $mentor->save();

    $user->userable_id = $mentor->user_id;
    $mentor->user()->save($user);

However, on the Users table, userable_id is being set to 0 while userable_type value is set to the corret value. The issue here is that save() sets it to a predefined 0. Any idea what's going on?



via kjanko

Advertisement