How to iterate in foreach() the data with Yii2 POST to arrange multi-boot data?

Hello. Organize the multiboot data, it all comes down to the fact that the user can select the category of features and services it provides, these services themselves may be several.

Decided not to use batchInsert(), and cost about AR, but in the end I get this error:
Call to a member function isAttributeRequired() on a non-object


It was found experimentally that the first 3 iterations pass with no problems, and they are only 3 and should be. But somehow start the 4th, which turns asepsis.

Of course, you could count the number of cells in the array and at last do break, but I want to do it right and to know specifically what the problem is.

Implemented code:
if($category->load(Yii::$app->request->post()) && $category->validate()){
 $services = Yii::$app->request->post('UserService');
 foreach ($services as $service){
 $new_service = new UserService();
 $new_service->user_id = Yii::$app->user->id;
 $new_service->service_id = $service['service_id'];
}
 }


In $services contains the following array:
array(3) {
[0]=>
 array(1) {
["service_id"]=>
 string(1) "1"
}
[1]=>
 array(1) {
["service_id"]=>
 string(1) "1"
}
[2]=>
 array(1) {
["service_id"]=>
 string(1) "1"
}
}
June 10th 19 at 16:20
1 answer
June 10th 19 at 16:22
Try to display the received data, and then convert them in a array and then use it in foreach.

And even better to use a Transaction when creating the model:
public function serviceCreate()
{
 if (!$this->validate()) {
 return null;
}

 $transaction = Yii::$app->db->beginTransaction();

 try {
 foreach ($services as $service){
 $new_service = new UserService();
 $new_service->user_id = Yii::$app->user->id;
 $new_service->service_id = $service['service_id'];
}
$transaction->commit();
 return true;
 } catch (\Exception $e) {
$transaction->rollBack();
 throw $e;
}
}

Find more questions by tags Yii