Exemple #1
0
 /**
  * 指定テーブルの外部キーを取得する
  *
  * @param  string $table_name
  * @return array
  */
 protected function getForeignKeys($table_name, $columns = null)
 {
     $fks = [];
     $sql = 'SELECT
           CONSTRAINT_NAME,
           TABLE_NAME,
           COLUMN_NAME,
           REFERENCED_TABLE_NAME,
           REFERENCED_COLUMN_NAME
         FROM information_schema.KEY_COLUMN_USAGE
         WHERE REFERENCED_TABLE_SCHEMA = DATABASE()
           AND REFERENCED_TABLE_NAME IS NOT NULL
           AND TABLE_NAME = ?
         ORDER BY POSITION_IN_UNIQUE_CONSTRAINT';
     $results = $this->db->build($sql, $table_name)->fetchAll();
     foreach ($results as $result) {
         if (!is_null($columns) && !in_array($result->COLUMN_NAME, $columns)) {
             continue;
         }
         $fk = new ForeignKey();
         $fk->setColumnName($result->COLUMN_NAME)->setRefTableName($result->REFERENCED_TABLE_NAME)->setRefColumnName($result->REFERENCED_COLUMN_NAME)->setConstraint($result->CONSTRAINT_NAME);
         $fks[] = $fk;
     }
     return $fks;
 }
Exemple #2
0
 /**
  * 外部キーを付与する
  *
  * @param  string $column_name  外部キーを指定したいカラム
  * @param  string $ref_table_name  指定先のテーブル名
  * @param  string $ref_column_name  指定先のカラム名
  * @param  array $options
  * @return Table
  */
 public function addForeignKey($column_name, $ref_table_name, $ref_column_name, $options = [])
 {
     $fk = new ForeignKey();
     $fk->setRefTableName($ref_table_name)->setColumnName($column_name)->setRefColumnName($ref_column_name)->setOptions($options);
     $this->foreignKeys[] = $fk;
     return $this;
 }