Getting all foreign keys of the table

Hello, I trying to get all foreign keys of the specify table, but when I do this:




        $sc = new CMssqlTableSchema();

        $sc->name = 'tbl_users';

        var_dump($sc->foreignKeys);die;



it display




array (size=0)

  empty



What I am doing wrong? :)

CDbTableSchema and its subclasses are simple data holders. They cannot connect to database and fetch metadata. Try this instead:




$sc = Yii::app()->db->schema->getTable('tbl_users'); // returns a CMssqlTableSchema instance populated with table data



var_dump of this equal to null :)

It means that the table doesn’t exist. Some possible reasons:

  • Table tbl_users doesn’t actually exist.

  • You have multiple databases associated with the application and Yi::app()->db connects to the wrong one. In this case use the appropriate connection.

  • I’m not familiar enough with MSSQL, but can it be a case-sensitivity issue?

Table exists in database, I even connected to database manualy, and tried to find table many ways because it have tabl prefix. Still null. I used code like:




$ccon = new CDbConnection('mysql:host=localhost;dbname=chooseone', 'root', '*******');

$ccon->schema->getTable('tbl_users'); // still null

$ccon->schema->getTable('users'); // null

$ccon->schema->getTable('{{users}}'); // null



What you get if you try to print the table names?




$ccon = new CDbConnection('mysql:host=localhost;dbname=chooseone', 'root', '*******');

$tableNames = $ccon->schema->getTableNames();

var_export($tableNames);



I try to get names of foreign keys to drop them by


CDbCommand -> dropForeignKey()

, but when I getting FK’s, them represented as array, there are missing name of fk, only fields and related table.

I don’t think Yii has built in support for it. If you really need this level of runtime database introspection you might want to try Doctrine DBAL. Its schema manager can provide a bit more detailed information about your database structure.