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

摘自: https://blog.csdn.net/wuhuagu_wuhuaguo/article/details/80330261
感谢这位朋友

!!!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();




查
http://www.kuitao8.com/20141104/3214.shtml
$db = Yii::app()->db;
$db->createCommand()->update('{{online}}',['addtime'=>$time,],'ip=:ip',[':ip'=>$ip])->getRawSql();
$db->createCommand()->update('{{online}}',['addtime'=>$time,],'ip=:ip',[':ip'=>$ip])->execute();
$db->createCommand()->update('table', ['field'=>':valuefield'], 'id_table=:id_table', [':id_table'=>$id_table, ':valuefield'=>$valuefield])->getRawSql();
$db->createCommand()->update('table', ['field'=>':valuefield'], 'id_table=:id_table', [':id_table'=>$id_table, ':valuefield'=>$valuefield])->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;
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容