ActiveRecord提供了一套面向對象的對數據庫進行增刪改查的方法,很實用,省去了select*的一系列操作
注意:一個ActiveRecord類對應一個數據表
首先來創建一個model,然後model內如下配置
<?php
namespace frontend\models;
use yii\db\ActiveRecord;
class Userinfo extends ActiveRecord
{
//這裏來配置連接的表名
public static function tableName()
{
return 'userinfo';
}
}
下面就可以開始對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() -> asArray() -> 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() ---- 條件查詢