Eloquent 用 where 语句删除所有行

Ste*_*eve 1 laravel eloquent

我想删除所有标记为“isOnly”的投票,这意味着文章是在全体会议之前投票的。

我写了这段代码,它删除了所有的选票。

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

删除带有标志“isOnly” == true 的所有选票的正确方法是什么

N69*_*69S 5

您可以使用 delete 调用堆栈 where 方法

$article->votes()->where('isOnly', true)->delete();
Run Code Online (Sandbox Code Playgroud)

一种更好的解决方案是避免将 foreach 放在一起,以便您只运行一个查询

$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
]);
Run Code Online (Sandbox Code Playgroud)

这将导致更快地处理您的 delete() 和 update()。