如何通过laravel从DB表中删除多行?

时间:2017-01-09 01:02:31

标签: php laravel-5

我想删除评论表中的所有评论。我这样做是通过这样做但这不是laravel方式。任何人都应该回答正确的步骤。

$comments = Comment::where('post_id',$id)->get();
    if(count($comments)>1)
    {
        $comment_id= [];
        foreach ($comments as $i)
        {
            $comment_id[] = $i->id;
        }
        for($i=0;$i<count($comments);$i++)
        {
            Comment::find($comment_id[$i])->delete();
        }
    }
    elseif (count($comments)==1)
    {
        $comments->delete();
    }

3 个答案:

答案 0 :(得分:2)

由于每个Eloquent模型都充当查询构建器,因此请尝试以下一行:

Comment::where('post_id',$id)->delete();

在修补程序中测试,按预期工作,返回已删除行的计数。

文档:https://laravel.com/docs/5.3/queries#deletes

答案 1 :(得分:-1)

您可以尝试以下方法:

public function deleteAll(Request $request)
{
    $ids = $request->ids;
    Comment::whereIn('id',explode(",",$ids))->delete();
}

答案 2 :(得分:-1)

s1<-data.frame (s1)
s1 = as.data.table(s1)
ggplot(data = s1, aes(x = year, y = rrP)) +
geom_col(data = s1[Mau <= 0], fill = "red") +
geom_col(data = s1[Mau >= 0], fill = "blue") +
theme_bw()

DB::table('users')->whereIn('id', $ids_to_delete)->delete();