Craft 3 - How do you programatically update a field type that is a Category? I have a Category element, locations, which I am trying to update programatically through a Craft 3 plugin that reads data from a CSV.

The locations category has a Field Layout: latitude (Number), longitude (Number), nearbyLocations (Categories).

I am having trouble updating a locations' nearbyLocations field. I am inserting an array of Categories into the nearbyLocations field on the setFieldValues() call.

A TypeError gets thrown deep in the bowels of Craft:


  craft\helpers\StringHelper::toLowerCase() must be of the type string, 
  array given, called in 
  /home/vagrant/code/vendor/craftcms/cms/src/helpers/Db.php on line 448


Below is my code:

$new_nearby_locations is an array of Category elements.



$new_nearby_locations = [];
foreach ($nearby_locations_slugs_from_csv as $nearby_location_slug) {
  $nearby_location = Category::find()
                    -&gt;slug($nearby_location_slug)
                    -&gt;one();

  if (!is_null($nearby_location)) {
      array_push($new_$nearby_locations, $nearby_location);
  }
}


Update $category's field values.

$category = Category::find()-&gt;slug($slug)-&gt;one();
$category-&gt;setFieldValues([
    'latitude' =&gt; $new_latitude, // previously defined
    'longitude' =&gt; $new_longitude, // previously defined        
    'nearbyLocations' =&gt; $new_nearby_locations
]);


Save the changes

 Craft::$app-&gt;elements-&gt;saveElement($category);


I am suspicious that updating nearbyLocations by inserting an array of Category elements is wrong. If so, what is the right format?

Or am I doing something else wrong.

Thanks in advance!
You should insert an array of ids - not an array of elements - in order to make it work. That's basically it

$new_$nearby_locations[] = $nearby_location-&gt;id;


(that's usually better than array push too)

Edit

But your error message sounds more like your slug is an Array or something like this. Do you change any other fields somewhere?