Blogger Information
Blog 40
fans 1
comment 0
visits 31832
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
关于子查询的总结
郭稳重啊的博客
Original
865 people have browsed it

主要功能:车辆名称搜索!!!主表:car(外键主要有shop_car_id)关联表分别有shop_car(car表进一步分类,外键:brand_id,type_id),car_brand(车辆的***表),car_brand_type(***的类型表 外键car_brand_id 车辆的类型)

此处需要接受一个参数 : $carName = input("searchValue");

1.联表将查询结果生成sql语句

 $car = Db::name("car")
   ->alias("car")
   ->join("shop_car t", "car.shop_car_id=t.id")
   ->field("car.id car_number_id,t.price,t.desc,car.lat,car.lng,t.brand_id,t.type_id")
   ->buildSql();

汇总:select(false); fetchsql(true)->select();生成不带括号的sql语句, 需要另加括号 $list = Db::table("(" . $car . ")as cars")
           buildSql 生成带括号的sql语句 $list = Db::table("$car as cars")

 第一步的运行结果:"( SELECT car.id car_number_id,`t`.`price`,`t`.`desc`,`car`.`lat`,`car`.`lng`,`t`.`brand_id`,`t`.`type_id` FROM `yisu_car_number` `car` INNER JOIN `yisu_shop_car` `t` ON `car`.`shop_car_id`=`t`.`id` )"

方法1:子查询+联表:

2.将子查询结果作新表cars继续联表查询

$list = Db::table($car . "cars")
   ->join("car_brand brand", "cars.brand_id=brand.id", "LEFT")
   ->join("car_brand_type types", "cars.type_id=types.id", "LEFT")
   ->field("cars.*,brand.*,types.*,brand.name brand_name,types.name types_name")
   ->page($this->page, 5)
   ->whereOr("types.name", "like", "%" . $carName . "%")
   ->whereOr("brand.name", "like", "%" . $carName . "%")
   ->select();

方法2:子查询+闭包
       $list = Db::table($car . "cars")
           ->whereOr('brand_id', 'IN', function ($query)use($carName) {
               $query->name('car_brand')->where("name","like","%".$carName."%")->field("id");
           })
           ->whereOr('type_id', 'IN', function ($query)use($carName) {
               $query->name('car_brand_type')->where("name","like","%".$carName."%")->field("id");
           })
           ->page($this->page, 5)
           ->select();

3.下面只需进行foreach遍历,数据重组

 $arr=[];//过滤不需要的数据

  foreach ($list as $k => $v) {
     $arr[$k]["title"] = $v["brand_name"].$v["types_name"];     
}

  return  $arr;

运行结果:

[

{

"title": "奥***迪Q5",

"price": "22.00",

"hotNum": 7,

"distance": "6525.4km"

},


{

"title": "奥***迪Q5",

"price": "33.00",

"hotNum": 4,

"distance": "6948.67km"

},


{

"title": "奥***迪A6",

"price": "89.00",

"hotNum": 1,

"distance": "0m"

},


{

"title": "奥***迪A6",

"price": "66.00",

"hotNum": 0,

"distance": "5726.73km"

},

{

"title": "奥***迪A6",

"price": "90.00",

"hotNum": 2,

"distance": "5726.73km"

}

]

备注:数据数据库自己添加的,跟实际车辆型号不一样请谅解!!!

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