【问题标题】:Array to string conversion laravel 7数组到字符串转换 laravel 7
【发布时间】:2020-04-30 06:25:53
【问题描述】:

我需要在数组中获取没有字符串的值。这将是字段的名称:

 static function showCust(){
   $table = DB::table("dummy_db.customer")->select("*")->paginate(10);
   $getFieldName = ["CUST_NAME", "CUST_CITY"];

   foreach($table as $items){
        $a[] = $items->$getFieldName[0];
   }
   dd($a);
}

但结果:

ErrorException Array to string conversion.

【问题讨论】:

    标签: php laravel eloquent laravel-7


    【解决方案1】:

    问题一:通过数组元素调用对象属性

    出现错误消息是因为$getFieldName作为变量,对象调用没有[0]的变量,你需要用大括号包裹$getFieldName[0]

    $items->{$getFieldName[0]};
    

    问题2:从分页器获取集合:

    您将paginate 应用于查询生成器,结果将是Illuminate\Pagination\LengthAwarePaginator 对象。

    如果您想将客户对象放入其中。你可以使用getCollection()方法来$table

       foreach($table->getCollection() as $items){
            $a[] = $items->${getFieldName[0]};
       }
    

    【讨论】:

    • 已解决,正在运行 $items->${getFieldName[0]};谢谢 Tsaitoga。
    【解决方案2】:

    如果您尝试仅使用键 CUST_NAME 检索 CUST_CITY 列表,您可以使用 pluck() 方法:

    $array = DB::table("dummy_db.customer")
        ->take(10)
        ->pluck('CUST_CITY','CUST_NAME');
    
    

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2020-09-10
      • 2018-05-10
      • 2017-05-10
      相关资源
      最近更新 更多