简体   繁体   中英

Convert SQL to Eloquent Query Builder : Laravel5.5

How can I convert this SQL to Laravel5.5 Eloquent format

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

Please observer the braces in the SQL

This is the one i wrote that returns a different sql when i tested the output using ->toSql

$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();

Find the SQL output from the query above

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

This output looks like the needed SQL, but the different is the braces on the SQL. so one coin the Eloquent Query Builder to come out with the braces on the query ?

Use the where() closure for parameter grouping :

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();

Try with this

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

Alexey Mezenin did it before me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM