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

£可爱£侵袭症+ 提交于 2019-12-12 03:29:05

问题


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 behind the scenes?


回答1:


Try this

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



回答2:


Try this to add data to Polymorphic relation (morphOne):

Migrations:

// User
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('nickname');
    $table->integer('administrator');
    $table->string('email');
    // add these two for the relation to work
    $table->integer('userable_id')->unsigned();
    $table->string('userable_type');
    //
    $table->rememberToken();
    $table->timestamps();
});

// Mentor
Schema::create('mentors', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
});

User Model

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

Mentor Model

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

Association Code:

$mentor = new Mentor();
// this is important: first save mentor
$mentor->save();

$userdata = [
    'first_name' => 'Trajce',
    'last_name' => 'Petkoski',
    'nickname' => 'ads',
    'administrator' => 0,
    'email' => 'asd',
    'password' => Hash::make('test')
 ];

$mentor->user()->create($userdata);

This works like a charm in my Laravel 5.4 test installation



来源:https://stackoverflow.com/questions/43209674/polymorphic-relation-morphto-save-not-recognizing-custom-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!