简体   繁体   中英

In Laravel, how do you bind parameters to a query in query builder DB raw inside another query?

I have two queries that I'm building:

$color = \DB::table('colors')->take(10)->orderBy('id', 'desc');

if(isset($between)){
    $color->whereBetween('id', [$start, $end]);
}

$flavor = \DB::table(\DB::raw('(' . $color->toSql() . ') as color'))
               ->join('flavor', 'flavor.color_id', '=', 'color.id')
               ->select('color.id', 'color.name', 'flavor.name');

return $flavor->get();

I need to bind 2 values in the first query only IF there is a $between set. And it has to be inside that \DB::raw .

How do I do that?

PS if I run the first query separately it works perfectly. But when I try to run the whole query at once I'm getting General error 2031 (basically the parameters are not bind).

You could try merging the bindings from the first query into the second query before executing it:

$flavor->mergeBindings($color);

Or just the binding without the 'type' of the bindings:

$flavor->addBinding($color->getBindings());

The second one should work because you only have a binding for a where which is the default type for addBinding . For more advanced queries with other bindings you probably want to go the way of merging the bindings so the 'type' of the binding is accurate.

Firstly, change your DB::table('color') to your Model name like

Color::take(10)->orderBy('id', 'desc')

Secondly, add

->mergeBindings($color->getQuery)

Something like this:

use App\Models\Color;
...
$color = Color::take(10)->orderBy('id', 'desc');

if(isset($between)){
    $color->whereBetween('id', [$start, $end]);
}

$flavor = \DB::table(\DB::raw('(' . $color->toSql() . ') as color'))
               ->mergeBindings($color->getQuery())
               ->join('flavor', 'flavor.color_id', '=', 'color.id')
               ->select('color.id', 'color.name', 'flavor.name');


return $flavor->get();

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