2016-07-08 18:07:01 5326次浏览 3条回答 0 悬赏 10 金钱

我是想判断表是否存在,然后添加表
但提示 Call to a member function createCommand() on a non-object
请问要怎么处理?

<?php
namespace frontend\controllers;
use yii\web\Controller;
use yii\db\Migration;
use yii\db\Schema;
class TableController extends Controller
{
    public function actionIndex()
    {
        $mir = new Migration();  
        $sch = new \yii\db\mysql\Schema;  
        $tableName='shang';

        $table=$db->createCommand("SHOW TABLES LIKE '".$tableName."'")->queryAll();
        if($table==null)        {
            echo '1';
        }else{
            echo '2';
        }

        // $mir->createTable('shang', [  
        //     'id' => 'pk',  
        //     'title' => $sch::TYPE_STRING . ' NOT NULL',  
        //     'content' => $sch::TYPE_TEXT,  
        // ]);  

    }

}
补充于 2016-07-08 20:02
$r = $db->getSchema()->getTableNames();//获取表名
$r = $db->getSchema()->getTableSchema('shang');//获取表字段名

这样返回的是数组,再判断,感觉这样也挺好的。

最佳答案

  • 花椒 发布于 2016-07-11 09:19 举报

    判断表是否存在有好多种方法,如:

    select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='dbname' and TABLE_NAME='tablename' ;
    或SHOW TABLES LIKE tableName
    

    判断表字段是否存在:

    SELECT * FROM information_schema.columns WHERE table_schema=CurrentDatabase AND table_name = 'tableName' AND column_name = 'column_name '
    
    
  • 回答于 2016-07-08 18:22 举报

    可以用migration里面的方法:

    $table=$db->createCommand("SHOW TABLES LIKE '".$tableName."'")->queryAll();//换成下面的 你的$db? 有点问题吧,是不是这样写Yii::$app->getDb()
    
    $mir->execute($sql);
    
    4 条回复
    回复于 2016-07-08 18:34 回复

    谢谢
    $db=Yii::$app->getDb();
    这要就可以了

    你知道怎样判断一个表字段是否存在吗?

    回复于 2016-07-11 10:12 回复

    谢谢!!!

    回复于 2016-07-11 10:30 回复

    这么及时的答案居然不是最佳?也是醉了

    回复于 2016-07-11 11:06 回复

    我点错了,你这个才是我想要的结果!!!
    ………………

  • 回答于 2018-07-04 18:34 举报
    User::getTableSchema()->name
    
您需要登录后才可以回答。登录 | 立即注册
okokad
经理

okokad

注册时间:2016-02-29
最后登录:2017-07-01
在线时长:49小时26分
  • 粉丝12
  • 金钱25
  • 威望80
  • 积分1315

热门问题