-1

There is this code:

            $new_city = $request->post("new_city_select"); 
            $city = City::find()  //find item by name
                ->where(['=', 'name', $new_city])
                ->one();;
            if ($city == null) {
                $city = new City;  //if item not exist, creating new
                $city->name = $new_city;
                $city->save();
                $city = City::find()
                    ->where(['=', 'name', $new_city])
                    ->one();
            }
            $model->saveCities($city); //save relation
            $model->save(false);

If an instance of "city" exists, then the connection many-to-many create is normal. But if not, then create a new instance of the "city" (in IF), but the connection is not established. How to fix it?

kome
  • 1
  • 2
  • 4

1 Answers1

0

from BaseActiveRecord - link() you must link them.

The call to link() will populate the junction table.

I'm not sure but I think this can fix your problem:

add this after save()

$model->link('city', $city);
ttrasn
  • 3,070
  • 4
  • 17
  • 30