Push/Add asset to Entry by asset filename I have spreadsheet that i'm parsing and I have available to me a Entry ID and the Asset filename. Can I add the asset to the entry by the filename?

Im targeting the product entry with:

$product = Entry::find()-&gt;section('products')-&gt;id($data[3]);
$productImages = ($product-&gt;productImages) ? $product-&gt;productImages : array();
$name = explode('?', basename($data[2])); 
$pushImageId = Asset::find()-&gt;filename($name[0])-&gt;id; // $name[0] = myfilename.jpg
$productImages = array_push($productImages,$pushImageId);
$product-&gt;productImages($productImages);
Craft::$app-&gt;elements-&gt;saveElement($product);


The handle for the asset field is:
productImages 

So when I run this i get this error:

Exception: Argument 1 passed to craft\services\Elements::saveElement() must implement interface craft\base\ElementInterface, instance of craft\elements\db\EntryQuery given

Thanks!

Solution

Based on the answer from robin in this question How to save Asset field of an Entry programmatically in Craft 3

It you just need to attach the asset ID's as an array. So i re-wrote the following code to create a new array of the original asset ids plus the new one. And it worked!

$product = Entry::find()-&gt;section('products')-&gt;id($data[3])-&gt;one();
$name = explode('?', basename($data[2]));
$pushImageIds = Asset::find()-&gt;filename($name[0])-&gt;ids(); // $name[0] = myfilename.jpg
$newProductImagesArray = array();
foreach($product-&gt;productImages as $image){
    array_push($newProductImagesArray,$image-&gt;id);
}
array_push($newProductImagesArray,$pushImageIds[0]);

$product-&gt;setFieldValue('productImages',$newProductImagesArray);
Craft::$app-&gt;getElements()-&gt;saveElement($product);
You need to fetch the asset and set it as a field value to your entry

$pushImageId = Asset::find()-&gt;filename($name[0])-&gt;ids();


id will display the id property of your query. You won't fetch any results with it ids() will return an array of asset ids

$product-&gt;setFieldValue ('productImages', $productImages);


Will set the relation and finally you can store the element

Edit: and you need to fetch the product as well. Currently you just create the query for it