laravel 像delete & update这样可以在多条记录上运行的方法

nzk0hqpo  于 2023-01-03  发布在  其他
关注(0)|答案(2)|浏览(156)

如何在模型中编写一个方法,并将其用于多个记录(如删除或更新)?

User::whereIn('id', [1, 2, 3])->delete();

我的方法是这样的:

public function remove()
{
    $this->update([
        'expired_at' => now()->addYear()
    ]);
}

但上述方法只能更新一条记录,我无法使用:

User::whereIn('id', [1, 2, 3])->remove();

我试试这个

public function remove()
{
    $this->update([
        'expired_at' => now()->addYear()
    ]);
}
nbysray5

nbysray51#

下面是基于laravel-9模型中的destroy()函数的实现方法:

用户模型(添加):(相应更改第31行)

/**
 * Update the models for the given IDs.
 *
 * @param  \Illuminate\Support\Collection|array|int|string  $ids
 * @return int
 */
public static function remove($ids)
{
    if ($ids instanceof EloquentCollection) {
        $ids = $ids->modelKeys();
    }

    if ($ids instanceof BaseCollection) {
        $ids = $ids->all();
    }

    $ids = is_array($ids) ? $ids : func_get_args();

    if (count($ids) === 0) {
        return 0;
    }

    // We will actually pull the models from the database table and call update on
    // each of them individually so that their events get fired properly with a
    // correct set of attributes in case the developers wants to check these.
    $key = ($instance = new static)->getKeyName();

    $count = 0;

    foreach ($instance->whereIn($key, $ids)->get() as $model) {
        //Do your update query here
        if ($model->update(['expired_at' => now()])) {
            $count++;
        }
    }

    return $count;
}

控制器调用:

//List of model IDs
User::remove([2, 3, 4, 5, 6]);

或者,如果你只想直接更新而不创建额外的逻辑,你可以像这样调用:

User::whereIn('id', [6, 7])->update(['expired_at' => now()]);

但是如果您希望处理比较日期、更改记录等复杂操作,那么可以根据需要修改foreach循环。

vltsax25

vltsax252#

你可以这样做

public function remove($ids)
{
    User::whereIn('id', $ids)->update([
        'expired_at' => now()->addYear()
    ]);
}

和Id的数组

$ids = [1, 2, 3];
User::remove($ids);

相关问题