mysql - 尝试插入belongsToMany关系

标签 mysql laravel laravel-4 eloquent

尝试插入belongsToMany关系:

$currentPerson->fbevents()->attach($currentEvent);

$currentPerson 是:

{
    "name": "xxxx",
    "userId": "yyyyyyy",
    "pictureUrl": "zzzzz"
}

显示 $currentPerson 没有 id,即使它刚刚使用 $currentPerson->save(); 插入到数据库中;

所以,我想问题是如何在数据透视表中获得正确的条目?模型是这样的:

用户.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();
});

最佳答案

只需将 attach() 替换为 save()

$currentPerson->save();
$currentPerson->fbevents()->save($currentEvent);

关于mysql - 尝试插入belongsToMany关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23547555/

相关文章:

php - 为什么此查询不显示任何信息?

angularjs - 在angular js中处理来自$resource的数据响应

php - Laravel Eloquent SQL 查询与 OR 和 AND 与 where 子句

php - 如何修复 laravel 5.2 这个错误 "Maximum function nesting level of ' 10 0' reached, aborting!"?

Laravel 4 SQL 日志/控制台

layout - Laravel 4 + 将变量传递给主布局

java - 如何在 hibernate java 中重新插入具有自动递增 id 的已删除记录

mysql - 数据库关系概念

mysql - 带有子查询的 sql select 语句(我认为)

php - laravel 4 eloquent 中的生命周期回调