【问题标题】:PHP - Laravel 4.2, ignore ->where('table.value','=',$value) if $value is emptyPHP - Laravel 4.2,忽略 ->where('table.value','=',$value) 如果 $value 为空
【发布时间】:2016-10-04 16:37:33
【问题描述】:

我正在学习laravel 4.2,对构造函数查询雄辩有疑问,我有以下代码

public static function filterInvoicingReport($valuesFilter){

    $fechaInicio='';
    $fechaFin='';
    $customerId='';
    $state='';
    if($valuesFilter == null)
        return;

    //obtenemos los valores de las variables dateRegisterStart y dateRegisterEnd
    if(array_key_exists('fechaInicio', $valuesFilter)&&array_key_exists('fechaFin', $valuesFilter)){
        $fechaInicio=$valuesFilter['fechaInicio'];
        $fechaFin=$valuesFilter['fechaFin'];
    }
    if(array_key_exists('customerId',$valuesFilter)){
        $customerId=$valuesFilter['customerId'];
    }
    if(array_key_exists('state',$valuesFilter)){
        $state=$valuesFilter['state'];
    }



    $sql= DB::table('invoice')
        -> select(
            'invoice.id_invoice',
            'invoice.invoice_number',
            'invoice.created_date',
            'invoice.name_seller',
            'invoice.conditions',
            'invoice.total_sale',
            'invoice.status',
            'invoice.customerId',
            'customer.name as customerName',
            'customer.identificationId as customerDNI')
        -> whereBetween(DB::raw('DATE_FORMAT(invoice.created_date,"%Y-%m-%d")'),[$fechaInicio,$fechaFin])
        ->Where('invoice.status','=',$state)
        ->Where('invoice.customerId','=',$customerId)
        -> join('customer','customer.customerId','=','invoice.customerId');
        -> get();
    return $sql;
}

是查询报表,问题是$state$customerId可以为空,查询返回全部为空。

我想要的是,如果 php 中的变量为空,则只返回 ->where 有一个不为空的变量。

【问题讨论】:

    标签: php laravel-4 eloquent


    【解决方案1】:

    where 子句中添加子查询:

        ->Where( function ($query) use ($state){ 
            if(!empty($state)) {
                $query->where('invoice.status','=',$state);
            } else {
                $query->whereNotNull('invoice.status');
            }
        })
        ->Where( function ($query) use ($customerId){ 
            if(!empty($customerId)) {
                $query->where('invoice.customerId','=',$customerId);
            } else {
                $query->whereNotNull('invoice.customerId');
            }
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      相关资源
      最近更新 更多