多态关系 - morphTo save()无法识别自定义主键

时间:2017-04-04 14:09:39

标签: php laravel laravel-5 eloquent laravel-eloquent

用户模型:

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

导师模特:

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

学生模型看起来与导师模型相同。

学生和导师的表包含一个名为user_id的自定义PK,它引用users表上的主键。

所以我要做的是以下内容:

    $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值设置为corret值。这里的问题是save()将它设置为预定义的0.任何想法在幕后发生了什么?

2 个答案:

答案 0 :(得分:0)

试试这个

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

答案 1 :(得分:0)

尝试将数据添加到多态关系(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测试装置中的魅力一样