yii2使用ActiveRecord类对数据库的操作

ActiveRecord提供了一套面向对象的对数据库进行增删改查的方法,很实用,省去了select*的一系列操作

注意:一个ActiveRecord类对应一个数据表

首先来创建一个model,然后model内如下配置

下面就可以开始对username表进行操作了

1.find()方法的使用

//获取表中所有数据信息并数组化
	public static function getallusermsg()
	{
        $model = self::find() -> asArray()  -> all();
		return $model;
	}
//按条件查询
    public static function getusermsg($username)
	{
        $model = self::find() -> asArray() -> where(['username' => $username]) -> one();
		return model;
	}
//数据库添加
    public static function setusermsg($userinfo)
    {
    	$userinfotable = new userinfo;
    	$userinfotable->username = $userinfo['username'];
    	$userinfotable->password = $userinfo['password'];
    	$userinfotable->role = $userinfo['role'];
    	if ($userinfotable->save()) {
    		return ['code' => 200,'message' => '注册成功!'];
    	} else {
    		return ['code' => 201,'message' => '注册失败!'];
    	}
    }
//数据库更新
    public static function setusermsg($username)
    {
    	$model = self::find() -> asArray() -> where(['username' => $username]) -> one();
        $model->username = 'suibian';
    	if ($model->save()) {
    		return ['code' => 200,'message' => '注册成功!'];
    	} else {
    		return ['code' => 201,'message' => '注册失败!'];
    	}
    }
//数据库删除
    public static function setusermsg($username,$password)
    {
    	$model = self::find() -> where(['username' => $username,'password' => $password]) -> one();
    	if ($model->delete()) {
    		return ['code' => 200,'message' => '注册成功!'];
    	} else {
    		return ['code' => 201,'message' => '注册失败!'];
    	}
    }

注:self为改类,asArray()是将所查数据数组化

2.ActiveRecord类常用的方法

all()/one() -----返回一条还是所有

orderBy()/andOrderBy() ----- 对数据进行排序

count() -----返回查询条件下的数据条数

with() -----指定关联表的字段

where()/andWhere()/orWhere() ---- 条件查询

你可能感兴趣的:(php)