如何获取 Laravel 中查询生成器结果的所有列的数组?

How to Get an Array of All of the Columns of a Query Builder Result in Laravel?

我正在尝试获取动态创建的列 table。我查看了 以了解如何获取列。

\DB::getSchemaBuilder()->getColumnListing(\DB::table('product_list')
    ->join('product_categories', 'product_list.product_category', '=', 'product_categories.id')
    ->join('product_types', 'product_list.product_type', '=', 'product_types.id')
    ->where('product_list.id', $this->id)
    ->orderBy('product_list.id', 'DESC')
    ->get()
);

但是,这给了我 [] 的输出。如果我 运行 命令没有用 \DB::getSchemaBuilder()->getColumnListing() 封装它,我得到这个:

Collection {#652 ▼
  #items: array:1 [▼
    0 => {#650 ▼
      +"id": 3
      +"cost": "150.00"
      +"product_category": 1
      +"product_type": 3
      +"product_score": 0
      +"created_at": "2019-01-16 16:34:29"
      +"updated_at": "2019-01-16 16:34:29"
      +"rating": 0
      +"down_payment": "10.00"
      +"title": "Static"
      +"price_start": "50.00"
      +"price_stop": "150.00"
      +"theme": "Custom"
      +"pages": 4
      +"rbac": 0
      +"portal": 0
      +"external_software": 0
      +"company_supplier": "Iezon Solutions"
    }
  ]
}

如何获得所有列的数组?

这可能是迄今为止最糟糕的解决方案,但我没有时间搜索集合文档以找到更好的方法或使用 [=18 完成它的方式=] 功能。

我决定将其转换 toArray(),使用第一个索引 [0] 并将其转换为数组。这让我可以使用 array_keys() 来查找列名。

array_keys((array) \DB::table('product_list')->join('product_categories', 'product_list.product_category', '=', 'product_categories.id')
            ->join('product_types', 'product_list.product_type', '=', 'product_types.id')
            ->where('product_list.id', $this->id)
            ->orderBy('product_list.id', 'DESC')->get()->toArray()[0])

如果您只需要动态创建的 table 列名称,一个快速的解决方案是:

array_keys(get_object_vars($collection->first())); // will output ['id', 'cost', 'product_category', ...]