XF 2.1 Understanding key and relationship in add-on's Setup.php file

asprin

Active member
So I'm creating a new table as part of my addon. In the setup file, I've the following code:
PHP:
public function installStep1()
{
    $this->schemaManager()->createTable('xf_mytable', function(Create $table)
        {
            $table->addColumn('id_category', 'int')->autoIncrement();
            $table->addColumn('category_title', 'varchar', '20')->setDefault('');
            $table->addColumn('status_id', 'int'); // this is the intended foreign key column that would reference `xf_anothertable.id_status` column
            $table->addPrimaryKey('id_category');
        });
}

From reading other threads, I came across three kinds of declarations for adding a key:
PHP:
 $table->addKey(['xxxxxx', 'yyyyy'], 'zzzzz'); // first format
 
 $table->addKey('xxxxxx'); // second format
 
 $table->addKey(['xxxxx', 'yyyyy']); // third format

I couldn't find the explanation of these formats in the docs. Any help as to which format will help me achieve my goal?
 
Okay, after running the installer via command line and observing the table structure, it appears that none of the above 3 formats add a relationship to another table. They are only used to add a index key with the same column name (first parameter which could either be an array or a string) or provide an alias for the key (the second parameter)

If that's true, how would I go about declaring the relationship inside the Setup.php file? Or is that it should be done via a Class located at src/addons/Addon-ID/Entity/MyTable.php that extends \XF\Mvc\Entity\Entity?
 
Last edited:
Generally speaking, you shouldn't need to use foreign keys in XF. You can define relationships as part of the entity's structure, if that's what you're after.
 
You can define relationships as part of the entity's structure, if that's what you're after.
So via a Class, right? Given the following:

xf_addonid_mytable.status (FK) references xf_addonid_myanothertable.id_status (PK)


Could this be enough?

PHP:
class MyAnotherTable extends \XF\Mvc\Entity\Entity
{
    public static function getStructure(Structure $structure)
    {
        $structure->table = 'xf_addonid_myanothertable';
        $structure->shortName = 'AddonID:MyAnotherTable';
        $structure->primaryKey = 'id_status';
        .
        .
        .
        $structure->relations = [
            'Statuses' => [
                'entity' => 'AddonID:MyTable',
                'type' => self::TO_ONE,
                'conditions' => 'status', 
                'primary' => true
            ]
        ];

        return $structure;
    }
}
 
Top Bottom