Suppose I have 2 models of AR. 1. Payment - payments 2. Cart - shopping cart

And accordingly, at payment

public function getCarts() { return $this->hasMany(Cart::className(), ['payment_id' => 'id']); } 

The task is as follows. I need to merge the basket of the second payment with the basket of the first.

those.

 $first_payment = Payment::findOne($first_payment_id); $second_payment = Payment::findOne($second_payment_id); 

And combine:

 $first_payment->carts = array_merge($first_payment ->carts, $second_payment->carts); 

And of course with this approach, I catch the error:

 Setting read-only property: frontend\models\Payment::carts 

That is basically logical.

Tell me how best to overwrite this property?

    2 answers 2

     foreach ($second_payment->carts as $cart) { $cart->payment_id = $first_payment_id; $cart->save(); } 
    • I do not need to make any changes to the database. - Radik Kamalov
    • @ RadikKamalov, why did you need to appropriate them then? O_o Just save the result of a merge into a variable. - PECHAPTER
    • The fact is that this assignment is not performed for all payments. I wanted the basket to be just payment-> carts, and not so that somewhere $ payments-> carts, somewhere $ payment-> custom_carts; - Radik Kamalov
    • Assign necessary for withdrawal. In short, there are such types of orders, where the order is 2, but visually for the user you only need to show one, only to combine their baskets - Radik Kamalov
    • @ RadikKamalov xs well then. You can just make a separate variable in the class for this. You are too smart to me. - PECHAPTER

    if I understand the problem correctly

     use yii\helpers\ArrayHelper; $first_payment = Payment::findOne($first_payment_id); $first_array = ArrayHelper::toArray($first_payment,[ 'frontend\models\Payment' => [ 'carts'=>'Carts', ], ]); $second_payment = Payment::findOne($second_payment_id); $second_array = ArrayHelper::toArray( $second_payment,[ 'frontend\models\Payment' => [ 'carts'=>'Carts', ], ]); $merge_payment = ArrayHelper::merge( $first_array, $second_array); 

    in the resulting array in cell merge_payment ['carts'] there will be an array with keys from the Carts properties, as a result of the merge, each key will contain an array of two values.

    • You must have the same Payment object at the output. Get an array of no trouble - Radik Kamalov