问题
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