Steve
Steve

Reputation: 645

Eloquent delete all rows with where statement

I want to delete all the votes where the flag "isOnly" is true which means the article is voted before the plenary session.

I have this code written, which deletes ALL the votes.

    foreach($commision->articles as $article) {
        $article->votes()->delete();
        $article->update([
            'isVoted' => false
        ]);
    }

What is the right way to delete all the votes with the flag 'isOnly' == true

Upvotes: 1

Views: 680

Answers (2)

Navid Anjum
Navid Anjum

Reputation: 92

Here is one way to delete by condition

$article->votes()->get()->filter(function($item){
     return $item->isOnly == true;
})->each(function($vote){$vote->delete();});

This statement will get all votes and apply filter funtion on votes which will give us votes which has isOnly == true rows. Then each function will delete returned votes. This will help. :)

Upvotes: -1

N69S
N69S

Reputation: 17205

You can stack where methods with delete call

$article->votes()->where('isOnly', true)->delete();

One better solution would be to avoid the foreach all together so you run only one query

$articleIds = $commision->pluck('articles.id'); //if the articles are already loaded calling a collection method pluck()
$articleIds = $commision->articles()->pluck('id'); // if articles are not loaded calling a query builder method pluck()
Votes::whereHas('article', function($articleQueryBuilder) use($articleIds) {
    $articleQueryBuilder->whereIn('id', $articleIds);
})->where('isOnly', true)->delete();
Article::whereIn('id', $articleIds)->update([
    'isVoted' => false
]);

This will result in a faster processing of your delete() & update().

Upvotes: 5

Related Questions