How to update a collection using Eloquent Laravel

前端 未结 2 1599
抹茶落季
抹茶落季 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'));
    
    0 讨论(0)
  • 2021-02-05 11:48

    You could try the update method on the \Illuminate\Database\Eloquent\Builder object:

    $queryBuilder = $device->commands()->whereStatus("pending");
    $queryBuilder->update(array("status" => "sent"));
    
    0 讨论(0)
提交回复
热议问题