当我使用sync()方法laravel在我的中间表中执行很多单独的插入查询,如下所示:
INSERT INTO `tag_user` (`user_id`, `tag_id`) VALUES ('59', '60')
INSERT INTO `tag_user` (`user_id`, `tag_id`) VALUES ('59', '61')
Run Code Online (Sandbox Code Playgroud)
我希望它像这样做一个多个插入:
INSERT INTO `tag_user` (`user_id`, `tag_id`) VALUES ('59', '60'), ('59', '61')
Run Code Online (Sandbox Code Playgroud)
可能吗?我正在使用MySql.如果attach()方法有接受数组的detach()方法会很好.有人这样做了吗?
这就是我解决它的方法:
在我的应用程序中,每个用户都有许多标签(多对多关系)。它称为toxi数据库模式。我的用户表称为“用户”,标签表称为“标签”。中间表称为“tag_user”,其中包含“tag_id”和“user_id”列。
用户模型:
class User extends \Eloquent
{
public static $timestamps = false;
public function tags()
{
return $this->has_many_and_belongs_to('Models\Tag');
}
}
Run Code Online (Sandbox Code Playgroud)
标签型号:
class Tag extends \Eloquent
{
public static $timestamps = false;
}
Run Code Online (Sandbox Code Playgroud)
sync()方法这就是我强迫 laravelsync()使用多个插入执行方法的方法:
//$currentUser is a model loaded from database
//Like this: $currentUser = Auth::user();
$newLinks = array();
$idsToSync = array();
foreach ($tags as $tag)
{
array_push($idsToSync, $tag->id);
}
//$currentUser->tags()->sync($idsToSync);
$currentIds = $currentUser->tags()->pivot()->lists('tag_id');
$idsToAttach = array_diff($idsToSync, $currentIds);
foreach ($idsToAttach as $value)
{
$newLink = array(
'user_id' => $currentUser->id,
'tag_id' => $value
);
$newLinks[] = $newLink;
}
if (count($newLinks) > 0)
{
\DB::table('tag_user')->insert($newLinks);
}
$idsToDetach = array_diff($currentIds, $idsToSync);
if (count($idsToDetach) > 0)
{
$currentUser->tags()->detach($idsToDetach);
}
Run Code Online (Sandbox Code Playgroud)
此代码执行一次多次插入,而不是多次插入。