Laravel Eloquent - 无法使用数组获取列

我正在使用 laravel eloquent 从多个列中获取数据。我正在使用数组从多个列中获取数据。为简单起见,我显示了两列的数据。

这是我的数据库表,其中包含callee_numbercaller_number

https://img1.mukewang.com/650421fe000122d212080717.jpg

这是我使用数组来获取列的代码:


    $paramArray = $params->all();


    $Caller_number = "";

    $Callee_number = "";


    if (isset($paramArray['Caller_number']) && $paramArray['Caller_number'] != '') {

        $Caller_number = $params->input('Caller_number');

    }

    if (isset($paramArray['Callee_number']) && $paramArray['Callee_number'] != '') {

        $Callee_number = $params->input('Callee_number');

    }


    if($Caller_number!=null){

        $querypart[] = "caller_number=$Caller_number";

    }

    if($Callee_number!=null){

        $querypart[] = "callee_number=$Callee_number";

    }



    $FinalQueryPart = '';

    if (!empty($querypart)) {

        

        $Seprator = "";

        foreach ($querypart as $querypartValue) {

            $FinalQueryPart .= $Seprator . $querypartValue;

            $Seprator = " AND ";

        }

    }


    $FinalQueryPart = trim($FinalQueryPart); //Output: "caller_number=783 AND callee_number=77"

    

但是,在上面的代码之后运行以下代码后,我收到错误:


    $gets = Tbcdrnew::where(function ($query) use ($FinalQueryPart) {

        $query->MIN('uniqueid')->where($FinalQueryPart)

            ->from('cdrnew');

            

    })->groupBy('uniqueid')->orderBy('Start_Date','DESC')->get();

错误如下:


Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'caller_number=783 AND callee_number=77' in 'where clause' (SQL: select * from `cdrnew` where (`caller_number=783 AND callee_number=77` is null) group by `uniqueid`

不明白我的代码中有什么问题。有人可以纠正我吗?


杨__羊羊
浏览 105回答 2
2回答

万千封印

我认为您在查询中犯了一个错误。将以下行替换为这些行:if($Caller_number!=null){    $querypart[] = "caller_number = '$Caller_number'";}if($Callee_number!=null){    $querypart[] = "callee_number = '$Callee_number'";}$Caller_number(请注意&上的单引号$Callee_number)。另外,使用该whereRaw()方法而不是where()按照响应评论中建议的方法。

杨魅力

我添加了一个答案,建议一种通过使用 Laravel 集合方法消除所有条件来简化代码的方法if。$query = Tbcdrnew::query();                           //start a query string based on Tbcdrnew model OR you could do DB::table('cdrnew');collect($paramArray)->filter(function($value, $key){  //convert paramArray into a collection    return $value != '';                              //filter all null and empty values})->each(function($value, $key) use ($query){         //iterate through all filtered values    $query->where(strtolower($key), $value);          //assuming array key is always column key in lowercase});$result = $query->groupBy('uniqueid')->orderBy('start_date','desc')->get();我不确定$query->MIN您的原始查询中是否有有效的查询生成器函数。
打开App,查看更多内容
随时随地看视频慕课网APP