Php Yii2不使用新项目保存多对多
有以下代码:Php Yii2不使用新项目保存多对多,php,yii2,many-to-many,yii2-model,Php,Yii2,Many To Many,Yii2 Model,有以下代码: $new_city = $request->post("new_city_select"); $city = City::find() //find item by name ->where(['=', 'name', $new_city]) ->one();; if ($city == null) {
$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中),但连接尚未建立。
如何修复它?从您必须链接它们
对link()的调用将填充连接表
我不确定,但我认为这可以解决您的问题:
在save()之后添加此项
$model->link('city', $city);