2014-05-08 62 views
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(); 
}); 
+0

显示表格模式和您创建这些条目的实际代码。 –

+0

我已经添加了模式 - 代码实际上就像我刚刚提到的那样,只是'$ currentPerson-> save();',它正确输入用户和id等,然后是'$ currentPerson-> fbevents() - >附加($ currentEvent);'。谢谢你的帮助。 – babbaggeii

+0

是的,什么是'$ currentEvent'? –

回答

0

仅仅通过save()

更换 attach()
$currentPerson->save(); 
$currentPerson->fbevents()->save($currentEvent);