具有列条件和更新的laravel模型块

table tname like below:

id name status 1 name1 0 2 name2 0 3 name3 0 4 name4 0

I create a model for the table above named Tname,then i want to chunk this table and change the 'status' in the table:

$midModel = Tname::where('status', 0);
$midModel->chunk(1, function ($rows)  {
foreach ($rows as $row) {
   Tname::where('id', $row->id)
        ->update([
              'status' => 1,
        ]);
}
});

After first row status was changed, 'chunk' will miss second row, my question is how to chunk with where('status', 0) and won't miss rows? i try to put where('status', 0) into then chunk, but it will chunk all the rows in the table every time.

You are actually doing wrong. You are selecting all the rows which has status 0 & then updating individually. It will take many query where else you can set all rows status 1 like this

Tname::update('status', 1)

This will update all rows regardless if there is any rows has status 0.

Try This:

This code will update all row status which value is 0 to 1

Tname::where('status', 0)->update(['status' => 1]);

Just came across a similar issue myself...

chunk works by running the query with an offset that goes up with each successive chunk, so if you are altering any columns that would change the underlying results of the query (i.e. status in your where clause), your offset will skip right over rows since your result set is now smaller than it was before.

The solution I came up with was to use take inside of a do...while loop, which avoids the offset issue.

do {
    $midModel = Tname::where('status', 0)->take(10)->get();

    foreach ($midModel as $row) {
        $row->update(['status' => 1]);
    }
while (count($midModel) > 0);