多态关系 - morphTo保存()不识别自定义主键 [英] Polymorphic relation - morphTo save() not recognizing custom primary key
问题描述
用户模型:
public function userable()
{
return $this->morphTo();
}
导师模型:
public function user()
{
return $this->morphOne('App\Models\User', 'userable');
}
学生模型看起来与导师模型相同。
The student model looks the same as the mentor model.
学生和导师的表包含一个名为user_id的自定义PK,它引用用户表上的主键。
The tables for Students and Mentors contain a custom PK called user_id which references the primary key on the users table.
所以我想要做的是:
$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);
但是,在Users表中,userable_id设置为0,而userable_type值设置为值。这里的问题是save()将其设置为预定义的0.任何想法在幕后发生什么?
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?
推荐答案
尝试添加数据到多态关系(morphOne):
Try this to add data to Polymorphic relation (morphOne):
迁移:
// 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();
});
用户模型
public function userable()
{
return $this->morphTo();
}
导师模型
public function user()
{
return $this->morphOne('App\Models\User', 'userable');
}
协会代码
$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);
这样做在我的Laravel 5.4测试安装中的魅力
This works like a charm in my Laravel 5.4 test installation
这篇关于多态关系 - morphTo保存()不识别自定义主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!