简体   繁体   English

在 Laravel 中,如何将参数绑定到另一个查询中的查询构建器 DB raw 中的查询?

[英]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.如果有$between集,我需要在第一个查询中绑定 2 个值。 And it has to be inside that \DB::raw .它必须在\DB::raw里面。

How do I do that?我怎么做?

PS if I run the first query separately it works perfectly. PS如果我单独运行第一个查询,它可以完美运行。 But when I try to run the whole query at once I'm getting General error 2031 (basically the parameters are not bind).但是当我尝试一次运行整个查询时,我得到了General error 2031 (基本上参数没有绑定)。

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 .第二个应该可以工作,因为您只有一个where的绑定,它是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.对于具有其他绑定的更高级查询,您可能希望 go 合并绑定的方式,因此绑定的“类型”是准确的。

Firstly, change your DB::table('color') to your Model name like首先,将您的DB::table('color')更改为您的 Model 名称,例如

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM