这给一试:
// Tree.php
public function perchBird($birdId)
{
$perched = $this->birds->pluck('id')->toArray();
$perched = array_combine($perched, array_fill(0, count($perched), ['index' => DB::raw('`index`+1')]));
$perched[$birdId] = ['index' => 1];
$this->birds()->sync($perched);
}
其分解:
1)获取已经栖息鸟类的IDS
$perched = $this->birds->pluck('id')->toArray();
2)创建栖息鸟类的关联数组IDS作为键和更新语句作为值,使用DB::raw
,以便Laravel了解它是MySQL计算,而不是本身的值。这样我们就可以采用现有的索引并增加它。
$perched = array_combine($perched, array_fill(0, count($perched), ['index' => DB::raw('`index`+1')]));
3)将新栖息鸟添加到数组中,索引为1。
$perched[$birdId] = ['index' => 1];
4)触发数据透视表同步
$this->birds()->sync($perched);
值得一提的是,sync
方法单独运行的每个更新语句,它可以根据栖息的鸟,你希望有数字高得惊人或者更新频率。另一种方法是,为增加索引做一个原始查询,然后又对栖息一个新的鸟:
public function perchBird($birdId)
{
DB::update('update bird_tree set `index` = (`index`+1) where tree_id = ?', [$this->id]);
$this->birds()->attach($birdId, ['index' => 1]);
}
不完全是口若悬河,按照要求,但仍然相当简单和可读性。
10x抱歉关于延迟我会尽快在我测试解决方案时批准答案+1 –