ThinkPHP查询语句与关联查询用法实例
本示例分享了ThinkPHP中查询语句及关联查询的具体应用方法,供读者参考学习。
在ThinkPHP框架开发中,可以直接编写SQL语句来完成数据库的读取与写入操作,下文将通过具体案例进行说明。
基础查询中,除字符串形式的条件外,利用数组和对象构建查询条件极为常见,这些是必须掌握的核心技能。
一、以数组形式设定查询条件 复制代码 代码如下:$User = M("User"); // 实例化User模型对象
$condition['name'] = 'thinkphp'; // 将查询条件传入方法 $User->where($condition)->select(); 二、采用对象方式进行查询 可使用任意对象,此处以内置stdClass为例
复制代码 代码如下:$User = M("User"); // 实例化User模型对象 // 定义查询条件 $condition = new stdClass(); $condition->name = 'thinkphp'; // 查找name字段值为thinkphp的记录 $User->where($condition)->select(); // 上述查询等价于 where('name="thinkphp"'),对象与数组查询效果一致且可
含where条件的常规查询 1、字符串格式
复制代码 代码如下:$user=M('user'); $list=$user->where('id>5 and id<9')->select(); $list=$user->where($data)->select(); 2、数组格式
复制代码 代码如下:$user=M('user'); $list=$user->where(array('username'=>'www.jb51.net'))->select(); $list=$user->where($data)->select(); 3、对象格式
复制代码 代码如下:$user=M('user'); $a=new stdClass(); $a->username='www.jb51.net; $list=$user->where($a)->select(); 双表关联查询:
复制代码 代码如下:$M_shopping = M('Shops'); $M_product = M('Product'); $list_shops = $M_shopping->join('as shops left join hr_product as product on shops.product_id = product.p_id') ->field('product.p_id,product.p_name,shops.product_amount,shops.product_id') ->where("shops.user_cookie='".$_COOKIE['hr_think_userid']."'") ->group('shops.id') ->select();
区间范围查询
复制代码 代码如下:$user=M('user'); $data['id']=array(array('gt',20),array('lt',23),'and'); $list=$user->where($data)->select(); 混合条件查询
复制代码 代码如下:$user=M('user'); $data['username']='pengyanjie'; $data['password']=array('eq','pengyanjie'); $data['id']=array('lt',30); $data['_logic']='or'; $list=$user->where($data)->select(); dump($list); 嵌套复杂查询
复制代码 代码如下:$user=M('user'); $data['username']=array('eq','pengyanjie'); $data['password']=array('like','p%'); $data['_logic']='or'; $where['_complex']=$where; $where['id']=array('lt',30); $list=$user->where($data)->select(); 三表关联查询
复制代码 代码如下:$M_shopping = M('Shops'); $M_product = M('Product'); $M_proimg = M('Product_image'); $list_shops = $M_shopping->join('as shops left join hr_product as product on shops.product_id = product.p_id left join hr_product_image as productimgon productimg.p_id = product.p_id')->fiel('productimg.pi_url,product.p_id,product.p_name,shops.product_amount,shops.product_id,product.am_id, product.p_procolor,product.p_price,product_amount*p_price as totalone')->where("shops.user_cookie='".$_COOKIE['hr_think_userid']."'") ->group('shops.id')->select(); 数据表查询条件设置 ① 直接将条件放入where子句,便于条件书写
复制代码 代码如下:$m_test = M("Product"); $productmeaage = $m_test->where("p_id='$proid'")->select();
② 另一种常用方法是使用数组封装条件
复制代码 代码如下:$M_product = M('Product'); $map['pid'] = $proid; $p_result = $M_product->where($map)->select();
希望上述内容能对各位在使用ThinkPHP框架进行程序设计时提供有益的帮助。