We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

how to save hasOne relation ?

AdminModel hasOne profile

    $this->hasOne('profileId', 'Cntysoft\Framework\UserCenter\Admin\Model\Profile', 'id',array(
           'alias' => 'profile',
            'foreignKey' => array(
                'action' => Relation::ACTION_CASCADE
            )
        ));

profile

     public function initialize()
    {
        $this->belongsTo('id', 'Cntysoft\Framework\UserCenter\Admin\Model\Admin', 'profileId', array('alias' => 'admin','foreignKey' => array(
                'action' => Relation::ACTION_CASCADE
            ))
        );
    }

i try like this

    $profile->assignBySetter(array(
           'recentApps'  => array(),
           'wallPaper'   => Constant::P_DEFAULT_WALLPAPER,
           'vdesktopNum' => Constant::P_DEFAULT_VD_NUM,
           'appVdMap'    => array(),
           'appVdOrder'  => array()
                ), true);
    $adminModel->profile = $profile;
    $adminModel->create();

Profile and admin data both are saved to database; but admin's profileId column is null , expect the new inserted profileid

My way I like this, it works , but is not beauty, Anyone has a better way? many thank

    $db = Kernel\get_db_adapter();
        try {
            $db->begin();
            $profile->create();
            $adminModel->setProfileId($profile->getId());
            $adminModel->assign($data);
            $adminModel->create();
            $db->commit();
        } catch (Exception $ex) {
            $db->rollback();
            throw $e;
    }
edited Apr '14

I think, this example has wrong model relation sides. AdminModel has a profileId field - so, maybe, AdminModel belongsTo Profile? And Profile hasOne AdminModel with its ID saved.

You can try to change model relation sides or replace AdminModel.profileId with Profile.adminId (and change relation fields for this).

edited Nov '20

You have inverted your relations. Try this instead,

AdminModel :

$this->belongsTo('profileId', 'Cntysoft\Framework\UserCenter\Admin\Model\Profile', 'id',array( 'alias' => 'profile', 'foreignKey' => array( 'action' => Relation::ACTION_CASCADE ) ));

Profile :

public function initialize() { $this->hasOne('id', 'Cntysoft\Framework\UserCenter\Admin\Model\Admin', 'profileId', array('alias' => 'admin','foreignKey' => array( 'action' => Relation::ACTION_CASCADE )) ); }