How to update a collection using Eloquent Laravel

前端 未结 2 1594
抹茶落季
抹茶落季 2021-02-05 11:04

I have a one to many relationship between Device and Command models (each Device has many commands). Now I want to update a c

2条回答
  •  独厮守ぢ
    2021-02-05 11:37

    Since $commands is a collection, changing the value of $commands->status will not have the effect that you intend (setting the value of status to 'sent' for every item in the collection).

    Instead, act on each item in the collection independently:

    foreach ($commands as $command)
    {
        $command->status = 'sent';
        $command->save();
    }
    

    You can also update the items in the database via Query Builder:

    DB::table('your_table')->where('status', 'pending')->update(array('status' => 'pending'));
    

提交回复
热议问题