jeudi 18 octobre 2018

How to set bindings for DB::raw?

In Laravel 5.7, I'm having an Eloquent query like this:

return User::findOrFail($userId)
    ->dogs()
    ->setBindings(['', '', '', '', $userId])
    ->get([
        'name',
        DB::raw('coalesce(birth_year, ?) <> ? as birth_year')
        DB::raw('coalesce(breed, ?) <> ? as breed')
    ]);

It's a little simplified example, but what I need in general, is passing the bindings to DB::raw().

My example works, but I don't like the fact that I need to manually overwrite $userId that is supposed to come naturally from user-dogs relation. Also, I don't like it that all bindings are together.

Is there a better way to use DB::raw like in my example? I know there is a selectRaw, but I don't want to select all the columns raw.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire