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

Laravel, update all relations when deleting a record

我有两个模型,PositionUser。他们之间有 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 还有要更新的