【发布时间】:2015-09-06 13:59:19
【问题描述】:
我有一个表,它只包含其他两个表的 id,我想要一个 n:m 关系,但现在每次我保存一条记录时,如果两个 id 之一已被使用,它会删除前一个记录。
我的迁移:
Schema::create('show_user', function(Blueprint $table) {
$table->integer('show_id')->unsigned()->index();
$table->foreign('show_id')->references('id')->on('shows');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users');
});
我的模特:
用户
public function shows()
{
return $this->belongsToMany('App\Show');
}
节目
public function users()
{
return $this->belongsToMany('App\User');
}
这就是我保存到数据透视表的方式:
User::find($userid)->shows()->sync([$showid, $userid])
当我在节目 5 上为用户 1(我)执行此操作时,它会保存 1 和 5,当我在节目 12 上为同一用户再次尝试时,它会保存 1 和 12,并从之前删除 1 和 5 记录.如果我通过 phpMyAdmin 手动插入,我可以添加多条记录,但不能使用同步。我也试过这个,结果相同:
User::find($userid)->shows()->sync([$showid])
【问题讨论】:
-
试试
attach()而不是sync()。
标签: mysql laravel eloquent laravel-5