<p>You can skip the <code>asArray()</code> part, as the object has all you need:</p>

<pre><code>// This bit returns only the query that defines what objects to get
$entryQuery = Entry::find()-&gt;section('inventory');

/*
 * This will get you one object, based on the query. 
 * Use all() if you want an array of objects
 */
$entry = $entryQuery-&gt;one();

// Of course, this could be written as
$entry = Entry::find()-&gt;section('inventory')-&gt;one();

/* 
 * Thanks to Yii2's magic getters and setters, 
 * and the way Craft uses them, any custom field can be 
 * obtained by using the field's handle:
 */
$customFieldContent = $entry-&gt;customFieldHandle;

/*
 * If the custom field is any kind of relation field (assets, categories, tags ...),
 * this custom field attribute would return a new query object.
 * You'd need to call all() or one() again to get the actual related objects:
 */
 $images = $entry-&gt;customImagesFieldHandle-&gt;all();

/*
 * To improve performance, you can eager load the images:
 */
$entry = Entry::find()
    -&gt;section('inventory')
    -&gt;with(['customImagesFieldHandle'])
    -&gt;one();

/*
 * ... which would result in an array of images as the value of the
 * customImagesFieldHandle attribute
 */
$images = $entry-&gt;customImagesFieldHandle;
</code></pre>

<p>Some light reading:</p>

<p><a href="https://docs.craftcms.com/v3/dev/element-queries/entry-queries.html" rel="nofollow noreferrer">About entry queries</a></p>

<p><a href="https://docs.craftcms.com/v3/dev/eager-loading-elements.html#eager-loading-image-transform-indexes" rel="nofollow noreferrer">About eager loading</a></p>

<p>Addition, after seeing exactly what it is you want. Use Craft's (or actually Yii's) <a href="https://www.yiiframework.com/doc/guide/2.0/en/helper-array#building-maps" rel="nofollow noreferrer">ArrayHelper map() function</a> to loop through your entries and mapping entry content to what you want:</p>

<pre><code>use craft\helpers\ArrayHelper

// Use the map() function to do what you want
$entries = Entry::find()-&gt;section('inventory')-&gt;all();

$entriesAsYouWantThem = ArrayHelper::map($entries, 'id', function($entry) {
    return (object)[
        'images' =&gt; $entry-&gt;images-&gt;all(), // or without all, if you use -&gt;with()
        'price' =&gt; $entry-&gt;price,
        'year' =&gt; $entry-&gt;year,
        ... All other fields
    ];
});
</code></pre>

CC BY-SA 4.0
2018-11-27T21:56:40.603Z
How would I create one dataset with the field data and the images in it? Also if I query just the section as an object there is not field data included in that set either. I need one set of data with the asset field (images) and all the other fields.
Radmation
CC BY-SA 4.0
2018-11-27T21:57:38.120Z
I think I may need to build out a string out on the server side. I guess I could loop through the results from the first query and in that loop get the assets for it and build some string? Ideally I would avoid that.
Radmation
CC BY-SA 4.0
2018-11-27T22:33:24.053Z
Well you put me on the right track. using the with didn't yield any of the fields i needed. I ended up querying all entries, looped over them and got the content i needed, and modified that entry to included what i needed. Thanks!
Radmation
CC BY-SA 4.0
2018-11-27T21:14:45.940Z
2018-11-28T10:26:55.093Z
2018-11-28T10:26:55.093Z
Paul
<p>Here is what I ended up doing. </p>

<pre><code>    $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()
        -&gt;section('inventory')
        -&gt;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-&gt;images-&gt;all(); // get all our images
        $price = $entry-&gt;price;
        $featured = $entry-&gt;featureThisVehicle;
        $make = $entry-&gt;make;
        $model = $entry-&gt;model;
        $year = $entry-&gt;year;
        $description = $entry-&gt;description;
        $inventoryStatus = $entry-&gt;inventoryStatus;
        $bodyStyle = $entry-&gt;bodyStyle;
        $color = $entry-&gt;color;
        $miles = $entry-&gt;miles;
        $vin = $entry-&gt;vin;
        $stkid = $entry-&gt;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);
</code></pre>

CC BY-SA 4.0
2018-11-28T10:27:52.053Z
See my addition for a simpler, shorter way to do this ...
Paul
CC BY-SA 4.0
2018-11-27T22:35:36.920Z
2018-11-27T22:35:36.920Z
Radmation
<p>I am trying to figure out how to return asset field(s) in a PHP entry query. Also if I could learn how to return "custom fields" when returning an Object that would be great too! Right now I am having to specify <code>asArray()</code> to even get access to most of my "custom fields" </p>

<p>As as example: I have a Vehicle Entry which has a custom field with the handle of price (number field) and another custom field (asset field) with the handle of images. When I execute the query without specifying the asArray() param I cannot find the custom fields included in the results. But if I specify asArray() then they are all there with the exception of my images field which I think is because it is an asset field or possible because it can be a collection of images? How can I make sure all the fields tied to an entry are returned in my query?</p>

<p>Here are some examples of queries and the corresponding results:</p>

<p>PHP Query <strong>without asArray()</strong>:</p>

<pre><code>$entry_query = Entry::find()
-&gt;section('inventory')
-&gt;all();
</code></pre>

<p>Returns: 
<a href="https://i.sstatic.net/S01K6.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/S01K6.png" alt="enter image description here"></a></p>

<p>PHP Query results <strong>with asArray()</strong>:</p>

<pre><code>$entry_query = Entry::find()
-&gt;section('inventory')
-&gt;asArray();
</code></pre>

<p><a href="https://i.sstatic.net/KjnWq.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/KjnWq.png" alt="enter image description here"></a></p>

<p>However even when specifing to make the result set an array I still cannot figure out how to include the 'images' field. </p>

<p>The images is a field added to the section (see below)
<a href="https://i.sstatic.net/Gwg8a.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Gwg8a.png" alt="enter image description here"></a></p>

<p>I am having a difficult time finding an answer via the documentation or an example of someone doing the same. All the examples i find are for the template side in twig. </p>

<p>Thanks!</p>

<craft3><query>
How to include asset fields in query in php?
# How to include asset fields in query in php?

(Asked by: username_0 on 2018-11-27)

I am trying to figure out how to return asset field(s) in a PHP entry query. Also if I could learn how to return "custom fields" when returning an Object that would be great too! Right now I am having to specify asArray() to even get access to most of my "custom fields" 
As as example: I have a Vehicle Entry which has a custom field with the handle of price (number field) and another custom field (asset field) with the handle of images. When I execute the query without specifying the asArray() param I cannot find the custom fields included in the results. But if I specify asArray() then they are all there with the exception of my images field which I think is because it is an asset field or possible because it can be a collection of images? How can I make sure all the fields tied to an entry are returned in my query?
Here are some examples of queries and the corresponding results:
PHP Query without asArray():
$entry_query = Entry::find()
->section('inventory')
->all();

Returns: 

PHP Query results with asArray():
$entry_query = Entry::find()
->section('inventory')
->asArray();


However even when specifing to make the result set an array I still cannot figure out how to include the 'images' field. 
The images is a field added to the section (see below)

I am having a difficult time finding an answer via the documentation or an example of someone doing the same. All the examples i find are for the template side in twig. 
Thanks!

**Tags:** craft3, query


---

## 2 answers

### Answer by username_1 on 2018-11-27. Score: 2

You can skip the asArray() part, as the object has all you need:
// This bit returns only the query that defines what objects to get
$entryQuery = Entry::find()->section('inventory');

/*
 * This will get you one object, based on the query. 
 * Use all() if you want an array of objects
 */
$entry = $entryQuery->one();

// Of course, this could be written as
$entry = Entry::find()->section('inventory')->one();

/* 
 * Thanks to Yii2's magic getters and setters, 
 * and the way Craft uses them, any custom field can be 
 * obtained by using the field's handle:
 */
$customFieldContent = $entry->customFieldHandle;

/*
 * If the custom field is any kind of relation field (assets, categories, tags ...),
 * this custom field attribute would return a new query object.
 * You'd need to call all() or one() again to get the actual related objects:
 */
 $images = $entry->customImagesFieldHandle->all();

/*
 * To improve performance, you can eager load the images:
 */
$entry = Entry::find()
    ->section('inventory')
    ->with(['customImagesFieldHandle'])
    ->one();

/*
 * ... which would result in an array of images as the value of the
 * customImagesFieldHandle attribute
 */
$images = $entry->customImagesFieldHandle;

Some light reading:
About entry queries
About eager loading
Addition, after seeing exactly what it is you want. Use Craft's (or actually Yii's) ArrayHelper map() function to loop through your entries and mapping entry content to what you want:
use craft\helpers\ArrayHelper

// Use the map() function to do what you want
$entries = Entry::find()->section('inventory')->all();

$entriesAsYouWantThem = ArrayHelper::map($entries, 'id', function($entry) {
    return (object)[
        'images' => $entry->images->all(), // or without all, if you use ->with()
        'price' => $entry->price,
        'year' => $entry->year,
        ... All other fields
    ];
});

> **Comments:**
> **username_0**: How would I create one dataset with the field data and the images in it? Also if I query just the section as an object there is not field data included in that set either. I need one set of data with the asset field (images) and all the other fields.  
> **username_0**: I think I may need to build out a string out on the server side. I guess I could loop through the results from the first query and in that loop get the assets for it and build some string? Ideally I would avoid that.  
> **username_0**: Well you put me on the right track. using the with didn't yield any of the fields i needed. I ended up querying all entries, looped over them and got the content i needed, and modified that entry to included what i needed. Thanks!  

---

### Answer by username_0 on 2018-11-27. Score: 1

Here is what I ended up doing. 
    $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);

> **Comments:**
> **username_1**: See my addition for a simpler, shorter way to do this ...  

---

