0
試圖插入belongsToMany關係:試圖插入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的類型是用戶,而$ 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();
});
顯示錶格模式和您創建這些條目的實際代碼。 –
我已經添加了模式 - 代碼實際上就像我剛剛提到的那樣,只是'$ currentPerson-> save();',它正確輸入用戶和id等,然後是'$ currentPerson-> fbevents() - >附加($ currentEvent);'。謝謝你的幫助。 – babbaggeii
是的,什麼是'$ currentEvent'? –