[英]Eloquent ORM Dynamic Where - Is there a shortcut / more elegant solution?
下面的代码是否有更优雅/更好的解决方案? 目前,我不得不重复很多查询,只是要在查询中添加一个额外的“ where”。
if ($common == true) {
$products = self::with(array(
'metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id){
$query->where('currency_id', '=', $currency_id);
}))
->where('metal_id', '=', $metal_id)
->where('product_type_id', '=', $product_type_id)
->where('common', '=', 1) // This line is the only difference
between the two Queries
->get();
}
else {
$products = self::with(array(
'metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id){
$query->where('currency_id', '=', $currency_id);
}))
->where('metal_id', '=', $metal_id)
->where('product_type_id', '=', $product_type_id)
->get();
}
首先,为什么要执行$common == true
?
其次,您不需要一次完成所有构建,这是您可以做到的。
PHP 5.3
$products = $this->with(
array('metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id)
{
$query->where('currency_id', '=', $currency_id);
}))
->where('metal_id', $metal_id)
->where('product_type_id', $product_type_id);
if ($common)
{
$products->where('common', 1);
}
$products = $products->get();
PHP 5.4
$products = $this->with(
['metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id)
{
$query->where('currency_id', '=', $currency_id);
}])
->where('metal_id', $metal_id)
->where('product_type_id', $product_type_id);
if ($common)
{
$products->where('common', 1);
}
$products = $products->get();
可以格式化得更好,但是您知道了。
Sinque Eloquent / QueryBuilder总是返回对自身的引用,您可以编写一个更优雅的版本,如下所示:
$query = self::with(array(
'metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id){
$query->where('currency_id', $currency_id);
}))
->where('metal_id', $metal_id)
->where('product_type_id', $product_type_id)
if ($common) {
$query = query->where('common', 1);
}
$products = $query->get();
怎么样
$products = self::with(array(
'metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id){
$query->where('currency_id', '=', $currency_id);
}))
->where('metal_id', '=', $metal_id)
->where('product_type_id', '=', $product_type_id)
->where('common', '=', (int)$common) // This line is the only difference
between the two Queries
->get();
}
这样,您就不需要if。 如果您一定不关心通用标志
$products = self::with(array(
'metal',
'metal.fixes.currency',
'metal.fixes' => function($query) use ($currency_id){
$query->where('currency_id', '=', $currency_id);
}))
->where('metal_id', '=', $metal_id)
->where('product_type_id', '=', $product_type_id);
$products = ($common) ? $products->where('common', 1)->get() : $products->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.