将SQL转换为Eloquent Query Builder:Laravel5.5

Oke*_*Eze 1 php sql laravel laravel-5

如何将此SQL转换为Laravel5.5 Eloquent格式

select * from 'arm_articles' where ('article_tag' like '%standard%' or 'article_topic' like '%standard%' or 'article_details' like '%standard%' or 'article_type' like '%standard%') and ( ('id' between 287 and 296) and 'article_active' = 1) order by 'id' desc

请观察SQL中的大括号

这是我写的一个,当我使用- > toSql测试输出时返回一个不同的sql

$post= PostModel::where('article_tag','like','%'.$contributor_id.'%')->orWhere('article_topic','like','%'.$contributor_id.'%')->orWhere('article_details','like','%'.$contributor_id.'%')->orWhere('article_type','like','%'.$contributor_id.'%')->whereBetween('id', [$end, $start-1])->where('article_active',1)->orderBy('id', 'desc')->take(10)->get();

从上面的查询中查找SQL输出

select * from 'arm_articles' where 'article_tag' like ? or 'article_topic' like ? or 'article_details' like ? or 'article_type' like ? and 'id' between ? and ? and 'article_active' = ? order by 'id' desc limit 10

此输出看起来像所需的SQL,但不同的是SQL上的大括号.那么Eloquent Query Builder就可以在查询中找到括号吗?

Ale*_*nin 5

使用where()闭包进行参数分组:

PostModel::where(function($q) use($contributor_id) {
        $q->where('article_tag', 'like', '%' . $contributor_id . '%')
          ->orWhere('article_topic', 'like', '%' . $contributor_id . '%')
          ->orWhere('article_details', 'like', '%' . $contributor_id . '%')
          ->orWhere('article_type', 'like', '%' . $contributor_id . '%');
    })
    ->whereBetween('id', [$end, $start - 1])
    ->where('article_active', 1)
    ->orderBy('id', 'desc')
    ->take(10)
    ->get();
Run Code Online (Sandbox Code Playgroud)