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

时间:2015-01-13 09:50:39

标签: php laravel eloquent one-to-many

我有两个模型,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字段始终保持不变。有更推荐的方式吗?

1 个答案:

答案 0 :(得分:2)

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

无论如何,我建议采用不同的方法,因为在循环中使用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时出现了一些错误(异常抛出)并且您执行了2个查询,则确保position不会更新,无论多少users需要更新。