1,判断数据表是否存在

  1. <?php
  2. $tableExist = \Yii::$app->getDb()->getTableSchema('{{archives}}'); //获取的名为archives表的整个对象
  3. //如果在migration中时
  4. $tableExist = $this->db->getTableSchema('{{archives}}');
  5. if($tableExist){
  6. echo "存在";
  7. }else{
  8. echo "不存在";
  9. }

2,判断表字段是否存在

  1. <?php
  2. $columnExist = \Yii::$app->getDb()->getTableSchema('{{archives}}')->getColumn('id'); //获取该表字段id的整个对象
  3. //如果在migration中时
  4. $columnExist = $this->db->getTableSchema('{{archives}}')->getColumn('id');
  5. if($columnExist){
  6. echo "存在";
  7. }else{
  8. echo "不存在";
  9. }

3,获取表所有字段

  1. <?php
  2. \Yii::$app->getDb()->getTableSchema('archives')->columns; //获取该表的所有字段对象数组集合
  3. \Yii::$app->getDb()->getTableSchema('archives')->columnNames; //获取该表的所有字段名称组成的集合