How to save data in the MySql tables with HAS_MANY relation by recursive way in Yii 1.7

120 views Asked by At

I have JSON data and i want to save all data in the database at once. The database schema shown in the image. so i can see here second order HAS_MANY relation . esaverelatedbehavior in yii allow me to save only first order data e.g. company_* . Is there any way to save all data to all tables at once ? enter image description here

1

There are 1 answers

1
Andrey Portnov On

It is not possible to insert data to many tables by one insert query

You have to use transactions to execute many inserts

public function saveJsonData()
{

    /**
     * parsing your json data
     */

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

    try {
        $company = new Company();
        $company->setAttributes($company_data);

        if (!$company->save()) {
            throw new Exception('some exception');
        }

        foreach ($otherCompanyRelatedDataList as $data) {
            $otherCompanyData = new OtherCompanyData();
            $otherCompanyData->setAttributes($data);
            if (!$otherCompanyData->save()){
                throw new Exception('some exception');
            }
        }

        /**
         *  save other data
         */


        $transaction->commit();

    } catch (Exception $e) {
        $transaction->rollback();
    }
}