我有两个模型,Position
和User
。它们之间有着One to many
关系。
当我删除一个职位时,我希望所有相关用户都从该职位分离并附加到另一个职位(通过 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
要更新,都不会更新。