我试图弄清楚如何在PHP条目查询中返回资产字段。另外,如果我可以学习如何在返回对象时返回“自定义字段”,那就太好了!现在,我必须指定asArray()才能访问我的大多数“自定义字段”
例如:我有一个Vehicle Entry,它有一个带有价格手柄的自定义字段(数字字段)和另一个带有图像手柄的自定义字段(资产字段)。在不指定asArray()参数的情况下执行查询时,找不到包含在结果中的自定义字段。但是,如果我指定asArray(),那么它们都存在,除了我的images字段,我认为这是因为它是一个资产字段,或者可能是因为它可以是一组图像?如何确保与条目绑定的所有字段都在查询中返回?
以下是一些查询示例和相应的结果:
没有asArray()的PHP查询:
$entry_query = Entry::find()
->section('inventory')
->all();
带有asArray()的PHP查询结果:
$entry_query = Entry::find()
->section('inventory')
->asArray();
但是,即使指定要使结果集成为数组,我仍然无法弄清楚如何包含“图像”字段。
我很难通过文档或某人这样做的例子来找到答案。我发现的所有示例都是针对树枝中的模板。
谢谢!
答案 0 :(得分:0)
这就是我最终得到的:
$vehicles = array(); // empty container to hold our modified entries
// Lets Query our Inventory - all of it
/** @var array $entry_query the name of our query to get our inventory - return a list of inventory after we execute query */
$entries = Entry::find()
->section('inventory')
->all();
foreach($entries as $entry) {
/*
* Let's get all our custom fields we want
* to include with our entries
*/
// Get our image field and add to result set - because it's an asset field this returns a query object
$ourimages = $entry->images->all(); // get all our images
$price = $entry->price;
$featured = $entry->featureThisVehicle;
$make = $entry->make;
$model = $entry->model;
$year = $entry->year;
$description = $entry->description;
$inventoryStatus = $entry->inventoryStatus;
$bodyStyle = $entry->bodyStyle;
$color = $entry->color;
$miles = $entry->miles;
$vin = $entry->vin;
$stkid = $entry->stkid;
// cast out entry object as an array - so we can add props to it
$entry = (array)$entry;
// add our custom fields to our newly casted entry array
$entry['images'] = $ourimages;
$entry['price'] = $price;
$entry['featured'] = $featured;
$entry['make'] = $make;
$entry['model'] = $model;
$entry['year'] = $year;
$entry['description'] = $description;
$entry['inventoryStatus'] = $inventoryStatus;
$entry['bodyStyle'] = $bodyStyle;
$entry['color'] = $color;
$entry['miles'] = $miles;
$entry['vin'] = $vin;
$entry['stkid'] = $stkid;
// Recast back to object just cause (not really necessary since we are json_encode'ing this)
$entry = (object)$entry;
array_push($vehicles, $entry);
}
return json_encode($vehicles);
答案 1 :(得分:0)
Yii的array helper function简化了这一过程。请参见此stack exchange entry-与您描述的方法基本相同,但是更简单(查询更少,代码行更少)。