简体   繁体   English

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

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

I am trying to get the columns of a dynamically created table. 我正在尝试获取动态创建的表的列。 I looked at this question to find how to get the columns. 我查看了这个问题,以查找如何获取列。

\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()
);

However, this is giving me an output of [] . 但是,这给了我[]的输出。 If I run the command without encapsulating it with \\DB::getSchemaBuilder()->getColumnListing() I get this: 如果我运行命令时未用\\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"
    }
  ]
}

How can I get an array of all of the columns? 如何获得所有列的数组?

如果只需要动态创建的表列名,则快速解决方案是:

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

This is probably by far the worst solution to use, but I don't have the time to search through the collection documentation to find a better method of doing this or the way its meant to be done using Laravel functionality. 这可能是迄今为止最糟糕的解决方案,但是我没有时间搜索集合文档以找到更好的方法或使用Laravel功能来实现此目的。

I decided to convert it toArray() , use the first index [0] and cast it to an array. 我决定将其转换为toArray() ,使用第一个索引[0]并将其转换为数组。 This then allows me to use array_keys() to find the column names. 然后,这使我可以使用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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM