尝试插入belongsToMany关系:
$currentPerson->fbevents()->attach($currentEvent);
$ currentPerson是:
{
"name": "xxxx",
"userId": "yyyyyyy",
"pictureUrl": "zzzzz"
}
显示$ currentPerson没有ID,即使它已被$currentPerson->save();
所以,我想问题是如何在数据透视表中获得正确的条目?模型是这样的:
user.php的:
public function fbevents()
{
return $this->belongsToMany('Fbevent', 'fbevent_user');
}
Fbevent.php:
public function users()
{
return $this->belongsToMany('User', 'fbevent_user');
}
$ currentPerson的类型为User,$ currentEvent的类型为Fbevent。
目前我收到以下错误:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`dmf`.`fbevent_user`, CONSTRAINT `fbevent_user_fbevent_id_foreign` FOREIGN KEY (`fbevent_id`) REFERENCES `fbevents` (`id`) ON DELETE CASCADE) (SQL: insert into `fbevent_user` () values ())
迁移架构:
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('userId');
$table->string('name');
$table->string('pictureUrl');
$table->timestamps();
});
Schema::create('fbevents', function(Blueprint $table) {
$table->increments('id');
$table->string('eventId');
$table->string('pageId');
$table->string('title');
$table->string('description', 500);
$table->datetime('start');
$table->datetime('end');
$table->string('picture');
$table->timestamps();
});
fbevent_user:
Schema::create('fbevent_user', function(Blueprint $table) {
$table->increments('id');
$table->integer('fbevent_id')->unsigned()->index();
$table->foreign('fbevent_id')->references('id')->on('fbevents')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
答案 0 :(得分:0)
只需将attach()
替换为save()
$currentPerson->save();
$currentPerson->fbevents()->save($currentEvent);