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

Model relation with foreign key on multi columns

Is there any way I can set relationship between models when there is a foreign key on multi columns?



22.6k

Not completely sure if I understand the question, but if you have foreign keys on several columns, you'd just do this:

class FirstModel extends \Phalcon\Mvc\Model {
    public $id;
    public $name;

    // Set up (reverse) relation.
    public function initialize() {
        $this->belongsTo('id', 'ThirdModel', 'first_model_id');
    }
}

class SecondModel extends \Phalcon\Mvc\Model {
    public $id;
    public $name;

    // Set up (reverse) relation.
    public function initialize() {
        $this->belongsTo('id', 'ThirdModel', 'second_model_id');
    }
}

class ThirdModel extends \Phalcon\Mvc\Model {
    public $id;
    public $first_model_id;
    public $second_model_id;

    // Set up relations on multiple columns.
    public function initialize() {
        $this->hasOne('first_model_id', 'FirstModel', 'id');
        $this->hasOne('second_model_id', 'SecondModel', 'id');
    }
}

This allows you to use the models like this:

<?php

// Retrieve FirstModel and SecondModel from a ThirdModel instance.
$model = new ThirdModel();
$relatedFirstModel = $model->getFirstModel();
$relatedSecondModel = $model->getSecondModel();

// Retrieve the ThirdModel from a FirstModel.
$model = new FirstModel();
$thirdModel = $model->getThirdModel();


2.6k

Thanks for your reply, dimhoLt, but this is not the case.

My case is like follows.

A MySQL table has a foreign key over two columns which references other table that has a primary key over two columns.