多个排序条件写法:
// order('条件1 升降序,条件2 升降序,……')
$Database->order('is_handle asc,created_at desc')->select();
不使用关联模型快速多表查询方法
用于数据量大,使用关联表要对两个表所有数据查询,性能降低;如果使用循环遍历获取另一张表的数据,就会要多次执行查询语句,性能也不好。所以使用in查询,只需查询两次数据库,再利用PHP快速遍历foreach来构造数据及大大优化性能。代码量多,但性能更优!
1、关联方法(小数据推荐)
class CompanyModel extends RelationModel{
protected $_link = array(
'City' => array(
'mapping_type' =>self::BELONGS_TO,
// 关联表的在查询表的外键
'foreign_key' => 'cid',
// 返回字段:更名不能有空格
'as_fields' => 'id:cityId,name:cityName',
),
);
}
2、直接方法(不推荐)
/*实例化模型*/
$Database = M('Company');
/*数据库查询*/
$list = $Database->order('establish')->select();
foreach ($list as $key => $value) {
$City = M('City');
$type = $City->where(array('id' => $value['cid']))->find();
$list[$key]['cityname'] = $type['name'];
$list[$key]['thumb'] = getImagePath('Company', $value['thumb']);
}
3、IN查询(推荐方法)
/*实例化模型*/
$Database = M('Company');
/*数据库查询*/
$list = $Database->order('establish')->select();
/*数据不能为0条,否则in查询错误*/
if (count($list) > 0) {
/*1、获取分类id数组*/
$cids = array();
foreach ($list as $key => $value) {
$cids[] = $value['cid'];
}
/*2、in查询分类*/
$City = M('City');
$typeList = $City->where(array('id' => array('in', $cids)))->select();
/*3、构建键值对,键为id 值为分类对象*/
$types = array();
foreach ($typeList as $key => $value) {
$types[$value['id']] = $value;
}
/*4、往原数据数组添加新字段*/
foreach ($list as $key => $value) {
$list[$key]['cityName'] = $types[$value['cid']]['name'];
$list[$key]['thumb'] = getImagePath('Company', $value['thumb']);
}
}