thinkphp关联预载入

  预载入的作用是减少执行sql语句,进而提升程序的性能。

public function join(){
//用于监听sql
     db::listen(function ($sql, $time, $explain) {
            // 记录sql
            echo $sql . ' [' . $time . 's]<br>';
            // 查看性能分析结果
            //dump($explain);
      });
//$brand = brand::all([3,4]);//未预载入  程序执行了5句sql语句
$brand = brand::with('goods')->select([3,4]);//预载入后  程序执行了4句sql语句
  foreach($brand as $b){
      foreach($b->goods as $good){
          echo $good->goods_name.":".$good->price."元<br>";  
      }
  }
}    

thinkphp关联统计

    关联统计只能用在一对多和一对多上,一对一的话还有上面好统计的。。。关联统计有相关的统计函数,除了whitcount()函数以外其他的统计函数都需要指定字段!!!

统计商品对应的数量

public function join(){
  $brand = brand::withcount('goods')->select([3,4]);
  foreach($brand as $b){
    //“方法名+_count”为系统自动生成的自动用于存储统计的值,也可自定义
    echo "品牌:"$b->brand_name."有"$b->goods_count."个商品<br>":
  }
}

统计商品中的最大值withmax()

public function join(){
    $brand = brand::withmax('good','price')->select();
    foreach($brand as $value){
       echo $value->brand_name"的品牌中最贵的商品价格为:".$value->goods_max;
    }
}

其它的统计方法

其它的统计方法有一下几种,其使用方法与上面类似

关联统计的方法 描述
withsum 求和
withavg 求平均值
withmax 求最大值
withmin 求最小值