laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Laravel HavingIn or grouping Having with AND - OR - Parentheses #2526

Open trijulio opened 3 years ago

trijulio commented 3 years ago

I know using having() queries is not very popular, but sometimes you need to use a group of having.

The having() function has the option to add a conditioner (AND, OR) but with just one OR will mess up your entire query. The only option is havingRaw() function, there is really few options for having() compared to where()

My proposal is to add more options for having() as there are for where().

In the meantime i made my on havingIn() hope someone find it helpfull.

This functions works like a scope for any model, and works the same as whereIn($column, $values)

Thanks.

public function scopeHavingIn($query, String $column, Array $values){

    $raw_string = '('.implode(' OR ', array_fill(0,count($values),"`".$column."` = ?")).')';

    return $query->havingRaw($raw_string, $values);
}
tpetry commented 3 years ago

The more correct approach would be to make having behave like where so that you could use a closure:

$model->having(fn ($query) => $query->wherein('column', [1,2,3]))

To be honest i didn't know yet that this is not possible which i expected.