Home > Mobile >  Does where() method have the same power like whereRaw() method?
Does where() method have the same power like whereRaw() method?

Time:12-10

I have a Video model and a Tag model. Let's say I would like to get all videos that have tags, maybe all the videos that have more than three relations with tags. I would do this:

Video::has('tags', '>=', 3)->get();

If I want do add more constrains, for example get all videos with at least 3 tags and the tag name should contain 'something'. I could do something like this:

Video::whereHas('tags' function(Builder $query){$query->where('name', 'like', '%something%');}, '>=', 3)->get();

But what if I would like to do something more, like only tags with odd/even id to be counted. Something like fmod('id', 2) to be used inside the closure. To check if the id is even or odd. Since I can't do something like: $query->where('id%2', '=', 0 );. Well, in this case I know I could use $query->where('name', 'like', '%something%')->whereRaw('tags.id%2=0');. But is there any other way using where() method?

CodePudding user response:

where() first parameter will always be the column, but in cases where you specifies columns in the queries like where() and select(), you can use DB::raw(); This should make this syntax viable, which i think is the best solution the Eloquent ORM.

->where(DB::raw('tags.id%2'), 0);
  • Related