Blogger Information
Blog 46
fans 3
comment 2
visits 39251
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
以实例演示:查询构造器中的10个最常用的方法 2018年5月23日
墨雨的博客
Original
745 people have browsed it

以实例演示:查询构造器中的10个最常用的方法
Table(),field(),order(),where(),limit(),insert(),insertAll(),update(),delete(),以及如何获取自增主键和数据打包方法data()

实例

<?php

namespace app\index\controller;
use think\Db;


/**
 * Description of query
 *
 * @author Dell
 */
class Query
{
        //查询一条记录
        public function find() {
                $res = Db::table('kc')->find(10);
                echo '查询kc表中主键id=10的记录<br>';
                print_r($res);
                $res = Db::table('kc')->where('kc_id', '>', 10)->find();
                echo '<br>查询kc表中主键kc_id>10的第一条记录<br>';
                print_r($res);
                $res = Db::table('kc')->field(['mc' => '品名', 'sl' => '数量', 'dw' => '单位', 'dj' => '单价'])
                                ->where('dj', 330)->find();
                echo '<br>查询kc表中单价=330的记录,限定输出字段并设置别名<br>';
                print_r($res);
        }
        //查询多条记录
        public function select() {
                
                $res = Db::table('kc')
                ->field(['mc'=>'品名','dj'=>'单价'])
                ->where('dj','>',200)
                ->order('dj','DESC')
                ->limit(5)
                ->select();
                echo '查询kc表中单价>200的记录,限定输出字段并设置别名,按单价降序排列,输出前5条记录<br>';
               dump($res);
        }       
        // 新增记录
        public function insert(){
                $data = ['mc'=>'方向盘','sl'=>3,'dw'=>'个','dj'=>110];
                $num = Db::table('kc')->insert($data);
                $id = Db::getLastInsID();
                return $num ? '成功添加'.$num.'条记录,ID为:'.$id : ',没有记录增加';
        }
        // 更新:必须基于前置查询,不允许无条件更新
        public function update(){
                $num = Db::table('kc')
                ->where('dj','<',10)
                ->data(['dj'=>Db::raw('dj+5')])
                ->update();
                return $num ? '成功更新'.$num.'条记录' : '没有记录被更新';
        }
        // 删除:不允许无条件删除,删除是一种危险操作,建议使用软删除
        public function delete(){
                $num = Db::table('kc')
                ->where('kc_id',19)
                ->delete();
                return $num ? '成功删除'.$num.'条记录' : '没有记录被删除';
        }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post