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

Relations and MySQL foreign key

I have models: Activity and Map, there is such relation: Activity:

    $this->hasOne('id', 'Activity\Map', 'activity_id', [
            'alias' => 'map',
            'reusable' => true,
            'foreignKey' => [
                'action' => Relation::ACTION_CASCADE
            ]
        ]);

Map:

        $this->belongsTo('activity_id', 'Activity\Activity', 'id', [
            'alias' => 'activity',
            'reusable' => true,
            'foreignKey' => [
                'allowNulls' => false,
                'message' => 'The activity doest not exist.'
            ]
        ]);

When I delete object Activity, then related Map is deleted also, this works fine. Should I create foreign key on database and table map? Because when I created such foreign key, then related Map was deleted via this FK, not via Phalcon relation. Which way is good?

Hmm... i aways do both... for me is important DB to have good relations and delete all lines from all related tables. In Models (phalcon) - i use relations to get related records. Sometime i need to use afterDelete in related model... so... use both :) I dont know why, just feel it better.

Good luck :)

edited Feb '16

Create database FK and maybe phalcon FK. I guess phalcon FK is mostly for databases which dont support FK ?

yes, i didnt think about that... point of view. Gj :)

When I have databse FK, then listeners on entities are not fired, because records are delete via database FK, not phalcon FK. So I shouldnt create database FK, but integration of data could be lost in that way.