gpt4 book ai didi

php - Laravel,删除记录时更新所有关系

转载 作者:行者123 更新时间:2023-12-02 01:01:40 25 4
gpt4 key购买 nike

我有两个模型,PositionUser。它们之间具有一对多关系。

当我删除一个位置时,我希望所有相关用户都从该位置分离并附加到另一个位置(通过 id 找到)。

我确信这很简单,但我已经尝试在 foreach 循环中执行此操作,但没有成功:

public function postDelete($position)
{
$positionMembers = $position->users()->get();

foreach ($positionMembers as $member) {
$member->position_id = '4';

// fixed copy/paste var name error
$member->save()
}

// Was the position deleted?
if($position->delete()) {
// Redirect to the position management page
return Redirect::to('admin/positions')->with('success', Lang::get('admin/positions/messages.delete.success'));
}

// There was a problem deleting the position
return Redirect::to('admin/positions')->with('error', Lang::get('admin/positions/messages.delete.error'));
}

我也试过:

$member->position()->associate($this->position->find(4));

但它也不起作用。 position_id 字段始终保持不变。有没有更推荐的方式?

最佳答案

首先定义没有成功,因为它什么也没说,而您显示的代码应该可以工作。

无论如何,我会建议不同的方法,因为在循环中使用 Eloquent save 不是最好的方法:

public function postDelete($position)
{
DB::transaction(function () use ($position, &$deleted) {

// run single query for update
$position->users()->update(['position_id' => 4]);

// run another query for delete
$deleted = $position->delete();
});

// Was the position deleted?
if($deleted) {
// Redirect to the position management page
return Redirect::to('admin/positions')->with('success', Lang::get('admin/positions/messages.delete.success'));
}

// There was a problem deleting the position
return Redirect::to('admin/positions')->with('error', Lang::get('admin/positions/messages.delete.error'));
}

有了这个,你可以确保 users 在删除 position 时出现错误(抛出异常)并且你执行了 2 个查询,无论有多少users 有待更新。

关于php - Laravel,删除记录时更新所有关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27919221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com