Mysql 尝试插入以下关系
正在尝试插入以下关系:Mysql 尝试插入以下关系,mysql,laravel,laravel-4,eloquent,Mysql,Laravel,Laravel 4,Eloquent,正在尝试插入以下关系: $currentPerson->fbevents()->attach($currentEvent); $currentPerson是: { "name": "xxxx", "userId": "yyyyyyy", "pictureUrl": "zzzzz" } 显示$currentPerson没有id,即使它刚刚通过$currentPerson->save插入数据库 所以,我想问题是如何在pivot表中获得正确的条目?模型如下: U
$currentPerson->fbevents()->attach($currentEvent);
$currentPerson是:
{
"name": "xxxx",
"userId": "yyyyyyy",
"pictureUrl": "zzzzz"
}
显示$currentPerson没有id,即使它刚刚通过$currentPerson->save插入数据库
所以,我想问题是如何在pivot表中获得正确的条目?模型如下:
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();
});
FBU事件用户:
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();
});
只需将“附加”替换为“保存”
在创建这些条目的位置显示表模式和实际代码。我已经添加了模式-代码与我所说的一样,只是$currentPerson->save;,正确输入用户和id等,然后$currentPerson->fbevents->attach$currentEvent;。谢谢你的帮助。是的,$currentEvent是什么?看起来你需要调用$currentEvent->save。确保事件和人员都已保存后,确保两者都具有id的echo$currentEvent->id;echo$currentPerson->id;。然后,您应该能够使用$currentPerson->fbevents->attach$currentEvent;将它们插入透视表;。
$currentPerson->save();
$currentPerson->fbevents()->save($currentEvent);