yii-besic (七)model 的使用

来源:互联网 发布:自己设计服装软件 编辑:程序博客网 时间:2024/05/16 01:12

首先在config/db.php去配置数据库

创建数据模型model/Test.php

<?php

namespace app/models;

use yii\db\ActiveRecord;

class Test extends ActiveRecord

{

      

}

?>

在控制器中

use app\models\Test;

在方法中执行原生sql  返回数组,数组中每条数据为对象形式

$sql=’select * from test where id=1’;

Test::findBySql($sql)->all();

可防止SQL注入 通过占位符

$sql=’select * from test where id=:id’;

Test::findBySql($sql,array(‘:id’=>$id))->all();

(一)单标查询

数组查询id=1

Test::find ()->where([‘id’=>1])->all();

数组查询id>0

Test::find ()->where([‘>’,’id’,0])->all();

数组查询id>=1 并且id<=2

Test::find ()->where([‘between’,’id’,1,2])->all();

数组查询title like “%title%”

Test::find ()->where([‘like,’title’,’title’])->all();

更多查询条件请查看官网www.yiichina.com/doc/api/2.0/yii-db-query#where()-detail

数据多的话转换数组

Test::find ()->where([‘like,’title’,’title’])->asArray()->all();

批量查询   batch()  表示一次查几条

foreach(Test::find()->batch(2) as $tests)

{

   print_r($tests)

} 

(二)单表删除

 

删除数据1

$res=Test::find ()->where([‘id’=>1])->all();

$res[0]->delete();

删除数据2 占位符

Test::deleteAll(‘id>:id’,array(‘:id’=>0));

(三)单表增加

$test=new Test

Id/title 为数据库字段名

$test->id=3;

$test->title=’title3’;

$test->save();

 

入库验证在model层 中写 验证id整型,title字符串型 0-5长度

public function rules(){

return[

[‘id’,’integer’],

[‘title’,’string’,‘length’=>[0,5]]

];

}

更多验证器www.yiichina.com/doc/guide/2.0/tutorial-core-validators

调用方式

$test=new Test

$test->id=3;

$test->title=’title3’;

$this->validate();

If($this->hasErrors())

{

    Echo ‘date is error!’;

Die;

}

$test->save();

(四)单表修改

 

$res=Test::find ()->where([‘id’=>1])->one();

$res->title=’titles’;

$res->save();

 

(五)关联查询

首先建立一个model Customer  同名数据库也建立  顾客表

<?php

namespace app/models;

use yii\db\ActiveRecord;

class Customer extendsActiveRecord

{

      

}

?>

然后建立领一个model Order  同名数据库也建立   订单表

<?php

namespace app/models;

use yii\db\ActiveRecord;

class Order extendsActiveRecord

{

      

}

?>

在控制器中

<?php

namespace app/controllers;

use yii\db\Controller;

use app\models\Order;

use app\models\ Customer;

class HelloControllerextends actionIndex{

       根据顾客表查询订单表

       $cus=Customer:;find()->where([‘name’=>’zhangsan’])->one();

Ord_id为order表中的 cus_id为customer的 两个id相互对应

       $ord=$cus->hasMany(‘app\models\Order;’,[‘ord_id’=>’cus_id’])->toArray->all();

              Order::className()   ===   app\models\Order

hasMany指1对多或多对多的关系    hasOne 指多对一或一对一

      

}

?>

 

 

为了使用model操作数据库

封装model Customer中

Public function getOrders()

{

$this->hasMany(Order::className(),[‘ord_id’=>’cus_id’])->toArray->all();

}

控制器中调用

$ord=$cus->getOrders();   

$ord=$cus->orders();

会默认调用getOrders()方法但是会在后面追加->all();

所以需要修改getOrders方法  去除->all();

替换原有的

$ord=$cus->hasMany(‘app\models\Order;’,[‘ord_id’=>’cus_id’])->toArray->all();


0 0