Saving Many_Many Relations With Auto-Incrementing Id

Hello everyone!

I’m struggling with many_many relations and auto incrementing id’s…

Everything is fine when a id is set manually in the form, but when I’m leaving the idfield (mysql, auto increment) blank, it creates a new record for Client, but not doesn’t create a record in GroupHasClient. This is probably caused because $model->getPrimaryKey() returns null. Same with $model->id

Any ideas?


	public function actionCreate()

	{

		$model = new Client;


		if(isset($_POST['Client']))

		{

			$model->attributes=$_POST['Client'];

			

			if($model->save()) {

				$client_id = $model->getPrimaryKey(); // problem here?

										

				if(isset($_POST['Client']['groups'])){

					$arr = $_POST['Client']['groups'];			

					if(count($arr)>0){

						foreach($arr as $group_id){

							$modelGroup = new GroupHasClient;

							$modelGroup->client_id = $client_id;

							$modelGroup->group_id = $group_id;

							$modelGroup->save();

						}

					}

				}

				$this->redirect(array('view','id'=>$model->id));

			}

		}


		$this->render('create',array(

				'model'=>$model,

		));

	}

I tried http://www.yiiframework.com/extension/save-relations-ar-behavior but same issue here. Works well when setting the id, but not with auto incrementing ids…

Best regards and thanks for any help!

If you successful created new record for client table. Find the latest record in Client table with the following criteria:


SELECT client FROM db ORDER BY id DESC LIMIT 1

or


SELECT LAST(id) FROM client

then continue your code. Hope that help :).

I think both is not reliable because the id can be set manually. It could happen that the ID is lower than the last existing id…

In your case, the id of the Client model not yet been set manually, so no worry :). Even if it happens, you still have its id number in $_POST[‘Client’][‘id’]. For this situation, change


$client_id = $model->getPrimaryKey();

to


$client_id = Client::model()->findByPk($_POST['Client']['id'])->getPrimaryKey();