jeudi 29 août 2019

Save a model with multiple relationships with dynamically added childrens

I have a problem trying to save a model with relationships where has dynamically add children as follows.

   $RatesPlansRoom = RatesPlansRooms::find(113);
    $calendarys = $RatesPlansRoom->calendarys()->whereBetween(
        'date',
        ["2019-08-29" ,"2019-09-10"]
    )->with([
        'rate'
    ])->get();
    $RatesPlansRoom->setRelation('calendarys', $calendarys);
    foreach ($this->getDateRange() as $dateInput) {
        $dateRates = $RatesPlansRoom->calendarys->first(function ($item) use ($date) {
            return $item->date == $date;
        });

        if (empty($dateRates)) { // create
            $dateRates = new RatesPlansCalendarys();
            $dateRates->date = $date;

            $RatesPlansRoom->calendarys->add($dateRates);
        }

        foreach ($rates as $rateType => $ratesType) {
            foreach ($ratesType as $rate) {
                $rateSelected = $dateRates->rate->first(function ($value) use ($rateType, $rate) {
                    return $value->num_adult == $rate['num_adult'];
                });

                if (empty($rateSelected)) {// create
                    $rateSelected = new Rates();
                    $rateSelected->fill($rate);

                    $dateRates->rate->add($rateSelected);

                } else {
                    $rateSelected->fill($rate);
                }
            }
        }
    }

    $RatesPlansRoom->push();

Throw the following error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (limatours_copia_pruebas.rates, CONSTRAINT rates_rates_plans_calendarys_id_foreign FOREIGN KEY (rates_plans_calendarys_id) REFERENCES rates_plans_calendarys (id)) (SQL: insert into rates (price_extra, updated_at, created_at) values (70, 2019-08-29 21:24:00, 2019-08-29 21:24:00))

It seems that in the relationship that must be created with

                $rateSelected = new Rates();
                $rateSelected->fill($rate);

                $dateRates->rate->add($rateSelected);

It is not filling the field "rates_plans_calendarys_id".



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire