企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 一对一关联 field选择字段 ``` ~~~ public function seo(){ return $this->hasOne('Seo','id','seo_id')->field('id,title,status'); } ~~~ ``` ![](https://img.kancloud.cn/8b/43/8b436943591cc1d0f9aefb78809eb09e_583x259.png) bind绑定关联表的属性到父模型属性 ``` ~~~ public function seo(){ return $this->hasOne('Seo','id','seo_id')->bind(['title']); } ~~~ ``` ![](https://img.kancloud.cn/55/05/55051d51912bb5c1647d8bf9d88dc56e_567x433.png) # 一对多关联 ``` ~~~ public function seo(){ return $this->hasMany('Seo','p_id','id'); } ~~~ ``` ![](https://img.kancloud.cn/dd/1b/dd1b88cd2229efe74dfabfbde458f96c_733x451.png) # 关联查询 ``` ~~~ ~~~ if(!empty($data['title'])){ $map[] = ['title','like',"%{$data['title']}%"]; } ~~~ $this->model->with('seo')->haswhere('seo',$map)->where($where)->select(); ~~~ ``` ![](https://img.kancloud.cn/53/0e/530e9d1ebaf9058d8b40803669ea06d8_1041x217.png) ![](https://img.kancloud.cn/48/90/4890ee1a8de1aa630ce74bd7946bb5f2_619x362.png) ~~~ # 模型关联查询数据 ~~~ $query = (new UserCommissionLog)->alias('c')->where(['customer_id' => config('sys.platform_id')]) // 收益类型 金额 账户余额 粉丝手机号 时间 来源 状态 应用类型 ->field('c.id, c.user_id, c.user_grade, c.amount, c.after_amount, c.create_time, c.order_type, c.status, c.app_type') ->whereIn('c.user_id', $user_ids) ->when(key_exists('status', $params), function (Query $query) use ($params) { $query->where(['c.status' => $params['status']]); }) ->when(key_exists('user_grade', $params), function (Query $query) use ($params) { $query->where(['c.user_grade' => $params['user_grade']]); }) ->when(key_exists('create_time', $params), function (Query $query) use ($params) { $tmpTime = explode(' - ', $params['create_time']); $query->whereBetween('c.create_time', [@$tmpTime[0], @$tmpTime[1]]); }) ->when(key_exists('mobile', $params), function (Query $query) use ($params) { $query->leftJoin('user u', 'u.id=c.user_id')->where(['u.mobile' => $params['mobile']]); }) ->with(['user' => function(Query $query) { $query->field('id, mobile'); }]) ->order('c.id desc')->paginate($this->limit); ~~~ # 模型关联 ``` ~~~ $data = $this->model->where(['id' => $id]) ->field('id, order_no, status, user_id, create_time, pay_time, pay_type, deliver_time, express_no, username, mobile, province, city, area, location, remarks, service_remarks') ->where(['customer_id' => config('sys.platform_id')]) ->with(['user' => function (Query $query) { $query->field('id, nickname, mobile'); }, 'order_details' => function (Query $query) { $query->field('goods_order_id, goods_image, goods_name, goods_code, goods_price, goods_num, goods_total_price, discount_price, freight_price, goods_total_price, real_price'); }]) ->find(); ~~~ ~~~ public function user(): HasOne { return $this->hasOne(User::class, 'id', 'user_id'); } public function orderDetails(): HasMany { return $this->hasMany(GoodsOrderDetail::class, 'goods_order_id'); } ~~~ ```