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 Relationships

Hi, When thinking about speed, it is better to use Phalcon's Virtual Foreign Keys or it is better to use mysql relationships ?

edited Mar '18

They don't do the same thing.

Phalcon VFK is for accessing related records with easily:

$user = User::findFIrst();
$language = $user->Language;
$language = $user->getLanguage();
$language = $user->getRelated('\MyModelNamespace\Language');

Mysql relationships, on the other hand, are there to ensure data integrity.

edited Mar '18

What about this ?

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Relation;

class Robots extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasMany(
            "id",
            "Parts",
            "robots_id",
            [
                "foreignKey" => [
                    "action" => Relation::ACTION_CASCADE,
                ]
            ]
        );
    }
}

https://olddocs.phalcon.io/en/3.0.0/reference/model-relationships.html#cascade-restrict-actions "Relationships that act as virtual foreign keys by default restrict the creation/update/deletion of records to maintain the integrity of data:"

I think the consistency of data and their relationships would be better in the database

However, if you need, for example, to delete a file from a related model and the related models will be cascaded. You must remove them before deleting the main model, since the database will delete the relation and then Phalcon will not find the records to be able to eliminate the models and the respective files.

Good luck

I've personally never used Phalcon's Virtual Foreign Keys. I use mysql's foreign keys all the time.

If speed is a concern when deleting, definitely go with mysql's foreign keys - that behaviour is much more optimized.