1

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 ?

2
  • Use parameter grouping Commented Feb 26, 2018 at 17:14
  • You can also use this online tool in oder to convert your raw SQL into Laravel Builder: midnightcowboycoder.com Commented Feb 26, 2018 at 17:16

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

1 Comment

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.