We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 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


     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

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

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 {
        } catch (Exception $ex) {
            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 )) ); }