yii2增删改查(model、db、Query三种方式) + mysql主从配置

!!!https://getyii.com/topic/219
==================
ExampleModel::findOne和findAll无法直接在后面->asArray(),因为这个方法已经写死了
find()->asArray()->all()/one()可以

public static function findOne($condition)
{
    return static::findByCondition($condition)->one();
}

public static function findAll($condition)
{
    return static::findByCondition($condition)->all();
}


public static function find()
{
    return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
}
===================
!!!https://blog.csdn.net/woshihaiyong168/article/details/53044322
!!https://www.yiiframework.com/doc/guide/2.0/zh-cn/db-query-builder 

http://www.yiichina.com/tutorial/996
http://www.yiichina.com/tutorial/834
https://www.jianshu.com/p/e89e9580fc67

------------------------------------------
//mysql主从配置:config/db.php
return 
[
    'class' => 'yii\db\Connection',

    // master 
    'dsn' => 'dsn for master server',
    'username' => 'master',
    'password' => '',

    // slaves
    'slaveConfig' => [
        'username' => 'slave',
        'password' => '',
        'attributes' => [
            // use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],

    'slaves' => [
        ['dsn' => 'dsn for slave server 1'],
        ['dsn' => 'dsn for slave server 2'],
        ['dsn' => 'dsn for slave server 3'],
        ['dsn' => 'dsn for slave server 4'],
    ],
]
------------------------------------------
//简单crud
$db=Yii::$app->db->createCommand(); 
$db->insert()->execute();
$db->batchInsert()->execute();
$db->delete()->execute();
$db->update()->execute();
//直接执行语句
Yii::$app->db->createCommand($sql)->queryAll();
//事务类提交
$transaction1 = $connection->beginTransaction();
try {
    $connection->createCommand($sql1)->execute();

    // internal
    $transaction2 = $connection->beginTransaction();
    try {
        $connection->createCommand($sql2)->execute();
        $transaction2->commit();
    } catch (Exception $e) {
        $transaction2->rollBack();
    }

    $transaction1->commit();
} catch (Exception $e) {
    $transaction1->rollBack();
}
------------------------------------------

(new \yii\db\Query())->find()
$StudentModel->find()
Student::find()
select()->all()/one()/each(100);
------------------------------------------


增
//普通插入
$user= new User;         
$user->username =$username;  
$user->password =$password;  
$user->save()

Yii::$app->db->createCommand()->insert('user', [  
    'name' => 'test',  
    'age' => 30,  
])->execute();



// 批量插入数据
Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [  
    ['test01', 30],  
    ['test02', 20],  
    ['test03', 25],  
])->execute();

Yii::$app->db->createCommand()->batchInsert(UserModel::tableName(), ['user_id','username'], [
    ['1','test1'],
    ['2','test2'],
    ['3','test3'],   
])->execute();



删
User::findOne($id)->delete();
//单个/批量 删除
Customer::deleteAll(['status' => 1], 'type = :type',[':type'=>1]);
$user = User::find()->where(['name' => 'test'])->one()/all()->delete();

Yii::$app->db->createCommand()
->delete('{{%user}}', 'user_id=:user_id', [':user_id' => $this->id])
   ->execute();

Yii::$app->db->createCommand()
->delete('{{%user}}', "user_id in($userIds) AND parent_id in($parentIds)")->execute();

User::find()->where(['name' => 'test'])->one()->delete();

User::deleteAll(['age'=>'30']);

Yii::$app->db->createCommand()
->delete('{{%user}}', 'user_id=:user_id', [':user_id' => $this->id])->execute();

Yii::$app->db->createCommand()
->delete('{{%user}}', "user_id in($userIds) AND parent_id in($parentIds)")->execute();


改
$user = User::find()->where(['name'=>'test'])->one();
$user->age = 40; //修改age属性值
$user->save();   //保存

// 直接修改:修改用户test的年龄为40
$result = User::model()->updateAll(['age'=>40],['name'=>'test']);

// 使用createCommand()修改
Yii::$app->db->createCommand()->update('user', ['age' => 40], 'name = test')->execute();


//runValidation boolen 是否通过validate()校验字段 默认为true。attributeNames array 需要更新的字段 
$model->update($runValidation , $attributeNames);  

Customer::updateAll(['status' => 1], 'status = 2'); 

Customer::updateAll(['status' => 1], ['status'=> '2','uid'=>'1']);


// 修改username
$user = User::findOne(1);
$user->username = test;
$user->save()/update();


// 单个/批量更新  team_num累加1
UserStats::updateAll(['team_num' => new Expression("team_num + 1")], ['in', 'user_id', $parentIds]);
//单个/批量更新
Customer::updateAll(['status' => 1], 'type = :type',[':type'=$type]);

// grade3 累加1
$db->createCommand()->update('yii_users', [
    'grade3' => $grade3 + 1
], 'user_id=:id', [':id' => $parentId])->execute();




查
简单查询
one/all/count/sum/average/min/max/scalar/column/exists/where/with/indexBy/asArray
Customer::find()->one();    此方法返回一条数据;
Customer::find()->all();    此方法返回所有数据;
Customer::find()->count();    此方法返回记录的数量;
Customer::find()->average();    此方法返回指定列的平均值;
Customer::find()->min();    此方法返回指定列的最小值 ;
Customer::find()->max();    此方法返回指定列的最大值 ;
Customer::find()->scalar();    此方法返回值的第一行第一列的查询结果;
Customer::find()->column();    此方法返回查询结果中的第一列的值;
Customer::find()->exists();    此方法返回一个值指示是否包含查询结果的数据行;
Customer::find()->asArray()->one();    以数组形式返回一条数据;
Customer::find()->asArray()->all();    以数组形式返回所有数据;
Customer::find()->where($condition)->asArray()->one();    根据条件以数组形式返回一条数据;
Customer::find()->where($condition)->asArray()->all();    根据条件以数组形式返回所有数据;
Customer::find()->where($condition)->asArray()->orderBy('id DESC')->all();    根据条件以数组形式返回所有数据,并根据ID倒序;
$customers = Customer::findAll(10);
$customer = Customer::findOne(10);
$customers = Customer::find()->where(['id' => 10])->all()/one();

$customers = Customer::findAll([10, 11, 12]);
$customers = Customer::find()->where(['IN','id',[10,11,12]])->all();
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();

$customers = Customer::findAll(['age' => 30, 'status' => 1]);
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
$customers = Customer::find()->where('age=:age AND status=:status', [':age'=>30, ':status'=>1])->all();
$customers = Customer::find()->where('age=:age AND status=:status')->addParams([':age'=>30,':status'=>1])->all();

$customers = Customer::find()->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();


$customers = Customer::find()->select('name, sex')->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();
$customers = Customer::find()->select(['name', 'sex'])->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();
$customers = Customer::find()->select(['xingming'=>'name', 'sex'])->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();
$customers = Customer::find()->select(['concat(firtname,'',lastname) as fullname', 'sex'])->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all();

//根据条件增加查询语句
$customerModel = new Customer();
$query = $customerModel->find()->select('id, name')->where(['status'=> 1]);
if (!empty($type)) $query->andWhere(['type' => $type]);
$query->asArray()->all();

// 返回 [100 => ['id' => 100, 'age' => '...', 'status' => ...], 101 => [...], 103 => [...], ...]
$customers = Customer::find()->indexBy('id')->where(['age' => 30, 'status' => 1])->all();

// 根据sql来查询:findBySql
$customers = Customer::findBySql('SELECT * FROM customer WHERE age=30 AND status=1 AND score>100 ORDER BY id DESC LIMIT 5,10')->all();

$count = Customer::find()->where(['age' => 30, 'status' => 1])->count();


关联查询
hasOne/hasMany:返回对应关系的1条/多条记录
====================================================
如下链接的文章讲得非常透彻,
https://www.cnblogs.com/yiifans/p/3786374.html 
我觉得a->hasOne(b,['b_id'=>'a_id'])只能查到b表的字段,没法查找a表的字段
就算joinWith可以查到a表和b表,但是查到的a表字段显示方式也很烦人,见下面例子,总得来说,多表联查还是只有Query方式靠谱:
class ItHelperEmailContent extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'it_helper_email_content';
    }

    public function getItHelper()
    {
        return $this->hasOne(ItHelper::className(), ['id' => 'email_id']);
    }
}


class ItHelper extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'it_helper';
    }
}

class test extends \yii\web\Controller
public function actionTest()
{
    $re = ItHelperEmailContent::find()->joinWith('itHelper')->asArray()->all();
    var_dump($re);die;
}

这里写图片描述

====================================================
//客户表Model:CustomerModel 
//订单表Model:OrdersModel
//国家表Model:CountrysModel
//首先要建立表与表之间的关系 
//在CustomerModel中添加与订单的关系

Class CustomerModel extends yiidbActiveRecord
{
    ...

    public function getOrders()
    {
        //客户和订单是一对多的关系所以用hasMany
        //此处OrdersModel在CustomerModel顶部别忘了加对应的命名空间
        //id对应的是OrdersModel的id字段,order_id对应CustomerModel的order_id字段
        return $this->hasMany(OrdersModel::className(), ['id'=>'order_id']);
    }

    public function getCountry()
    {
        //客户和国家是一对一的关系所以用hasOne
        return $this->hasOne(CountrysModel::className(), ['id'=>'Country_id']);
    }
    ....
}

// 查询客户与他们的订单和国家
CustomerModel::find()->with('orders', 'country')->all();

// 查询客户与他们的订单和订单的发货地址
CustomerModel::find()->with('orders.address')->all();

// 查询客户与他们的国家和状态为1的订单
CustomerModel::find()->with([
    'orders' => function ($query) {
        $query->andWhere('status = 1');
        },
        'country',
])->all();


findOne()和findAll():
// 查询key值为10的客户
$customer = Customer::findOne(10);
$customer = Customer::find()->where(['id' => 10])->one();
// 查询年龄为30,状态值为1的客户
$customer = Customer::findOne(['age' => 30, 'status' => 1]);
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
// 查询key值为10的所有客户
$customers = Customer::findAll(10);
$customers = Customer::find()->where(['id' => 10])->all();
// 查询key值为1011,12的客户
$customers = Customer::findAll([10, 11, 12]);
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
// 查询年龄为30,状态值为1的所有客户
$customers = Customer::findAll(['age' => 30, 'status' => 1]);
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
==============================================
//findOne()错误写法
$ItHelper = ItHelper::findOne([
    'type' => ItHelper::TYPE_VPN,
    'ucid' => $ucid,
    ['in', 'status', [ItHelper::STATUS_NOCHECK, ItHelper::STATUS_CHECKING]]
]);
//改正
$ItHelper = ItHelper::find()
        ->where(['type' => ItHelper::TYPE_VPN, 'ucid' => $ucid])
        ->andwhere(['in', 'status', [ItHelper::STATUS_NOCHECK, ItHelper::STATUS_CHECKING]])
        ->one();
==============================================

where()条件:
$customers = Customer::find()->where($cond)->all(); 

$cond = ['type' => 1, 'status' => 2]
$cond = ['id' => [1, 2, 3], 'status' => 2] 
$cond = ['status' => null]

//and
$cond = ['and', 'id=1', 'id=2']
$cond = ['and', 'type=1', ['or', 'id=1', 'id=2']]

//or
$cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]

//not
$cond = ['not', ['attribute' => null]]

//between
$cond = ['between', 'id', 1, 10]

//in
$cond = ['in', 'id', [1, 2, 3]]
$cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]]
$cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]

//like
$cond = ['like', 'name', 'tester']
$cond = ['like', 'name', ['test', 'sample']]
$cond = ['like', 'name', '%tester', false]

//exists
$cond = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]

//运算符
$cond = ['>=', 'id', 10]
$cond = ['!=', 'id', 10]




User::find()->select('user_id,user_name')->where(['uid'=>'1'])->asArray()->one() 
User::find()->select('username')->where(['uid'=>'1'])->scalar(); 

User::find()->select('*')->where(['>=', 'admin_id', 10])->offset(0)->limit(10)->all()

$subQuery = (new Query())->select('COUNT(*)')->from('user');    
$query = (new Query())->select(['id', 'count' => $subQuery])->from('post');

User::find()->select('user_id')->distinct();


$model = TopNews::find()
    ->where(['and', ['<=', 'start_time', $time], ['>=', 'end_time', $time], ['=', 'status', 1]])
    ->asArray()->all();

$model = (new \yii\db\Query())
            ->from('{{%article}}')
            ->select('art_id, title, updated_at, image')
            ->where(['cat_id' => $cat_id, 'status' => 1])
            ->orderBy('sort_order Desc')
            ->offset($offset)
            ->limit($size)
            ->all();

//join 
$models = (new \yii\db\Query())
            ->select('u.id, u.username, u.realname, u.email, u.status, u.group_id, g.group_name')
            ->from('{{%user}} as u')
            ->join('left join', '{{%user_group}} as g', 'u.group_id = g.group_id')
            ->where(['u.parent_id' => $userId])
            ->offset($offset)
            ->limit($size)
            ->all();

// groupBy
$models = Contract::find()
            ->select("confirm_time, sum(money) as total_money")
            ->where(['status' => 1])
            ->groupBy(['FROM_UNIXTIME(confirm_time, \'%Y-%m\')'])
            ->having(['FROM_UNIXTIME(confirm_time, \'%Y-%m\')' => $month])
            ->all();


//查看执行sql
echo UserModel::find()->where(['status'=>1])->createCommand()->getRawSql();
查看是否报错
var_dump(UserModel::getErrors());






delete('{{student}}', ['in','id',[1,2,3]])



update('{{student}}', ['grade'=>'99'], ['xingming'=>$xm,'xingbie'=>$xb])
update('{{student}}', ['grade'=>'99'], 'xingming=:xm and xingbie=:xb', [':xm'=>$xm,':xb'=>$xb])


(new \yii\db\Query())->from($this->tableNetworkingStoreMonth)
->where(['=', 'date', $month])->andWhere(['=', 'store', $store])->count('id');

(new \yii\db\Query())->select(['sum(`num`) as `nums'])->from($table)
->where('`date`=:date')
->addParams([':date' => $date])
->andWhere(['in', 'store', $storeArray])



$StudentModel->find()->select('date'.$str)
->where(['and', ['>=', 'date', $start_date], ['<=', 'date', $end_date]])
->groupBy('date')->orderBy('date asc')->asArray()->all();


Student::find()->select('orgCode, lng, lat')
->where(['treeLevel' => $treeLevel])->asArray()->all();


$result = $TrafficModel->find() ->select('date'.$str)
->where(['and', ['>=', 'date', $start_date], ['<=', 'date', $end_date]])
->groupBy('date')->orderBy('date asc')->asArray()->all();

二、查询构造器 — (new \yii\dn\Query())
详见:https://www.yiiframework.com/doc/guide/2.0/zh-cn/db-query-builder

$rows = (new \yii\db\Query())
    ->select(['id', 'email'])
    ->from('user')
    ->where(['last_name' => 'Smith'])
    ->limit(10)
    ->all();


select 
组建查询时没有调用 select() 方法,那么选择的将是 '*' , 也即选取的是所有的字段。
$query->select(['id', 'email']);//等同:$query->select('id, email');

$query->select(['user.id AS user_id', 'email']);//等同:$query->select('user.id AS user_id, email');

$subQuery = (new Query())->select('COUNT(*)')->from('user');
$query = (new Query())->select(['id', 'count' => $subQuery])->from('post');
//等价于: SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`


$query->select(['id', 'username'])->addSelect(['email']);

$query->select('user_id')->distinct();

数组方式2点好处,后同:
(1)可以使用数组的键来表示字段的别名。
$query->select(['user_id' => 'user.id', 'email']);
(2)数据库表达式
$query->select(["CONCAT(first_name, ' ', last_name) AS full_name", 'email']);


from
$query->from('user');

$query->from(['public.user u', 'public.post p']);//$query->from('public.user u, public.post p');

$query->from(['u' => 'public.user', 'p' => 'public.post']);

$subQuery = (new Query())->select('id')->from('user')->where('status=1');
$query->from(['u' => $subQuery]);
//等价于:SELECT * FROM (SELECT `id` FROM `user` WHERE status=1) u 


where
$query->where('status=1');

$query->where(['status' => 1, 'type' => 2]);

$query->where('status=:status', [':status' => $status]);

$query->where('YEAR(somedate) = 2015');

$query->where('status=:status')->addParams([':status' => $status]);
if (!empty($search)) {
    $query->andWhere(['like', 'title', $search]);
}
其中:[操作符, 操作数1, 操作数2, ...]
操作符:andor、between、not between、innot in、like、or like、not like、or not like、exists、not exists
>, <=


$query->where("status=$status");//危险!千万别这样干,会引起sql注入。除非你非常的确定 $status 是一个整型数值。


 andWhere 或者 orWhere 在原有条件的基础上 附加额外的条件

filterWhere 或者 andFilterWhere 或 orFilterWhere
//例如,在一个可以通过用户名或者邮箱搜索的表单当中,用户名或者邮箱 输入框没有输入任何东西,这种情况下你想要忽略掉对应的搜索条件, 那么你就可以使用 filterWhere() 方法来实现这个目的
 $query->filterWhere([
    'username' => $username,
    'email' => $email,     
]);



andFilterCompare :它可以根据值中的内容智能地确定运算符
$query->andFilterCompare('name', 'John Doe');
$query->andFilterCompare('rating', '>9');
$query->andFilterCompare('value', '<=100');
$query->andFilterCompare('name', 'Doe', 'like');



orderBy
$query->orderBy([
    'id' => SORT_ASC,
    'name' => SORT_DESC,
]); //等价于:  $query->orderBy('id ASC, name DESC');

$query->orderBy('id ASC')->addOrderBy('name DESC');



groupBy
$query->groupBy(['id', 'status']);//等价于: $query->groupBy('id, status');

$query->groupBy(['id', 'status'])->addGroupBy('age');





having
$query->having(['status' => 1]);

andHaving 或 orHaving
$query->having(['status' => 1])->andHaving(['>', 'age', 30]);




limit和offset
$query->limit(10)->offset(20);



join
$query->join($type,$table,$on,$params);
$type: 连接类型,例如:'INNER JOIN', 'LEFT JOIN', 'RIGHT JOIN'
$table: 将要连接的表名称
$on:可选,连接条件
$params:可选,与连接条件绑定的参数。
$result = (new \yii\db\Query())
    ->select('a.article_id, a.title')
    ->from(ArticleScenarios::tableName().' as s')
    ->join('left join', ArticlePublished::tableName().' as a', 'a.article_id = s.article_id')
    ->where('s.scenario_id = :scenatio and s.status = :status and a.type = :type ')
    ->addParams([':scenatio' => $scenario, ':status' => self::ARTICLE_SCENARIO_PUBLISHED, ':type' => ArticlePublished::TYPE_ARTICLE])
    ->orderBy('s.created_at desc')
    ->all();

$query->leftJoin() 
$query->rightJoin() 
$query->innerJoin() 
//除了连接表以外,你还可以连接子查询。
$subQuery = (new \yii\db\Query())->from('post');
$query->leftJoin(['u' => $subQuery], 'u.id = author_id');



union
$query1 = (new \yii\db\Query())
    ->select("id, category_id AS type, name")
    ->from('post')
    ->limit(10);

$query2 = (new \yii\db\Query())
    ->select('id, type, name')
    ->from('user')
    ->limit(10);

$query1->union($query2);

返回结果集
all():将返回所有行
one():返回结果集的第一行。
column():返回结果集的第一列。
scalar():返回结果集的第一行第一列的标量值。
exists():返回一个表示该查询是否包结果集的值。
count():返回 COUNT 查询的结果。
其它: sum($q), average($q), max($q), min($q) 等。$q 是一个必选参数, 既可以是一个字段名称,又可以是一个 DB 表达式。
$row = (new \yii\db\Query())
    ->from('user')
    ->where(['like', 'username', 'test'])
    ->one();
注意: one() 方法只返回查询结果当中的第一条数据, 条件语句中不会加上 LIMIT 1 条件。如果你清楚的知道查询将会只返回一行或几行数据 (例如, 如果你是通过某些主键来查询的),这很好也提倡这样做。但是,如果查询结果 有机会返回大量的数据时,那么你应该显示调用 limit(1) 方法,以改善性能。 例如, (new \yii\db\Query())->from('user')->limit(1)->one()。


查看由 yii\db\Query 对象创建的 SQL 语句
$command = (new \yii\db\Query())
    ->select(['id', 'email'])
    ->from('user')
    ->where(['last_name' => 'Smith'])
    ->limit(10)
    ->createCommand();

// 打印 SQL 语句
echo $command->sql;
// 打印被绑定的参数
print_r($command->params);

// 返回查询结果的所有行
$rows = $command->queryAll();



索引查询结果
// 返回 [100 => ['id' => 100, 'username' => '...', ...], 101 => [...], 103 => [...], ...]
$query = (new \yii\db\Query())
    ->from('user')
    ->limit(10)
    ->indexBy('id')
    ->all();

//使用表达式的值做为索引
$query = (new \yii\db\Query())
->from('user')
->indexBy(function ($row) {
    return $row['id'] . $row['username'];
})->all();




批处理查询(可降低内存的占用率)
use yii\db\Query;
$query = (new Query())
    ->from('user')
    ->orderBy('id');
// 一次查询100条,即:$users 是一个包含100条或小于100条用户表数据的数组
foreach ($query->batch() as $users) {}
// 一次查询1条,即:$user 是用户表当中的其中一行数据
foreach ($query->each() as $user) {}



//指定索引的批处理查询 
$query = (new \yii\db\Query())
    ->from('user')
    ->indexBy('username');
foreach ($query->batch() as $users) {
    // $users 的 “username” 字段将会成为索引
}
foreach ($query->each() as $username => $user) {
}
阅读更多
个人分类: yii2
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭