schroedingerswg
1 week ago

Cannot sync laravel many-to-many relation properly

Posted 1 week ago by schroedingerswg

I'm trying to update quantity and an array by appending values, if already attached. Somehow it doesnt seem to work. See commit: https://gitlab.com/domezi/s2/-/commit/d7602a07271001ad8b39d1afd65dbc148e918c93

My code:

        //implement
        $this->products()->attach($product,["quantity"=>$quantity,"product_single_ids"=>json_encode($product_single_ids)]);

        $old_relation = $this->products()->find($product->id);
        if($old_relation != null) {

            // only upadte quantity and sns
            $old_relation = $this->products()->find($product->id);
            $this->products()->sync(
                [
                    $product->id  =>  [ 
                        "quantity"          => $old_relation->pivot->quantity + $quantity,
                        "product_single_ids"=> json_encode(
                            array_merge($product_single_ids, json_decode($old_relation->pivot->product_single_ids))
                        )
                    ]
                ]
            );

        } else {
            $this->products()->attach($product,["quantity"=>$quantity,"product_single_ids"=>json_encode($product_single_ids)]);
        } 

Thank you very much!!

Please sign in or create an account to participate in this conversation.