Том*_*раћ 2 php one-to-many laravel eloquent
我有两个模型,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'));
}
Run Code Online (Sandbox Code Playgroud)
我也试过:
$member->position()->associate($this->position->find(4));
Run Code Online (Sandbox Code Playgroud)
但它也不起作用。position_id 字段始终保持不变。有没有更推荐的方法?
首先定义没有成功,因为它什么也没说,并且您显示的代码应该可以工作。
无论如何,我会建议不同的方法,因为save在循环中使用 Eloquent并不是最好的方法:
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'));
}
Run Code Online (Sandbox Code Playgroud)
有了这个,你可以确保users如果删除时出现一些错误(抛出异常)position并且你执行 2 个查询,无论有多少users要更新,都不会更新。
| 归档时间: |
|
| 查看次数: |
2444 次 |
| 最近记录: |