企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[thinkphp - 虚无缥缈的云 - 博客园 (cnblogs.com)](https://www.cnblogs.com/lichihua/p/9477845.html) product\_image   商品图片表: ![](https://img.kancloud.cn/13/d1/13d1a384014db364b88e710e44c5c91c_408x307.png) product\_property  商品属性表 ![](https://img.kancloud.cn/02/6a/026ab58d59690fe54a937cc23d42e3df_575x196.png) product   商品表: ![](https://img.kancloud.cn/94/af/94af42762696f1a7bd03d01c80008143_855x265.png) ``` //product->controller //获取单个商品 public function getOne($id) { (new IDMustBePositiveInt())->goCheck(); $product=ProductModel::getProductDetail($id); //$product的mysql数据为空很能是getProductDetail方法里没有添加find(), if(!$product){//(这里返回的是think\db\Query对象)这里判断的时候一定要确定返回的是不是数据集 如果是则用$product_isEmpty()判断 throw new ProductException(); } return $product; } //product->model public static function getProductDetail($id) { //千万不能在with中加空格,否则你会崩溃的 //多个关联第一个参数里用,隔开,参数名就是下面定义关联的的方法 //如果不报错获取不到 properties 的话可能是 ProductProperty模型里定义的表名不正确(protected $table='...')、或者with('imgs','properties')这种 //imgs.imgUrl:当前模型的imgs方法关联了ProductImage模型,而ProductImge模型的imgUrl方法又关联了Image模型 so... $products=self::with('imgs.imgUrl,properties')->find($id); //或者这种写法 //$products=self::with(['imgs.imgUrl','properties'])->find($id); //又或者: /* $products=self::with(['imgs.imgUrl']) ->with(['properties']) ->find($id); */ //无法进行排序需要修改如下 $products=self::with([ 'imgs'=>function($query){ $query->with(['imgUrl']) ->order('order','asc'); } ])->with(['properties']) ->find($id); return $products; } /** * 关联商品详图 * call to a member funftion eagerlyResult() 当没有加return返回时 报此错 * @return [type] [description] */ public function imgs() { return $this->hasMany('ProductImage','product_id','id'); } /** * 关联商品属性 * @return [type] [description] */ public function properties() { return $this->hasMany('ProductProperty','product_id','id'); } //ProductImage ->model class ProductImage extends BaseModel{ protected $table='product_image'; protected $hidden=['img_id','detele_time','product_id']; //关联image public function imgUrl() { return $this->belongsTo('Image','img_id','id'); } } //ProductProperty ->model class ProductProperty extends BaseModel{ protected $table='product_property'; protected $hidden=['product_id','detele_time','id']; } ```