zoukankan      html  css  js  c++  java
  • YII 多表联查 纵表

    A id 与B a.id 

    B id 与C b.id

    C id 与D c.id

    查A读D数据

    应用场景:

    order表 ordergoods表 goods表 merchant加盟商

    order 与ordergoods 通过 order_id字段关联:
    ordergoods与goods表通过goods_id 和id关联:
    goods与merchant表通过merchant_id 和id关联

    在order表 model里 建立关联
    public function getOrderGoods()
    {
    return $this->hasMany(OrderGoods::className(), ['order_id' => 'order_id']);//一个order关联多个ordergoods
    }

    ordergoods与goods表通过goods_id 和id关联:
    在ordergoods表model里 建立关联
    public function getGoods()
    {
    return $this->hasOne(Goods::className(), ['id' => 'goods_id'])->select(['lb_goods.id','lb_goods.picture','merchant_id','merchant_name'])->joinwith(['merchant'],false);//一个ordergoods关联一个goods(并通过joinwith关联merchant加盟商表)lb_goods 需要写表前缀 不然无法识别id是哪个表的
    }

    goods与merchant表通过merchant_id 和id关联:
    在goods表merchant里 建立关联
    public function getMerchant()
    {
    return $this->hasOne(Merchant::className(), ['merchant_id' => 'id']);//一个goods关联一个merchant;
    }

    在controller引用时:
    $orderinfos = OrderInfo::find()
    ->joinWith(
    ['orderGoods'=>function($query){
    $query->joinWith(['goods']);//ordergoods关联goods表(goods表已经在getGoods()方法关联merchant加盟商表)
    }]
    )
    ->where('添加条件')
    ->all()

    总结 : 在controller通过joinwith内回调 order表可以查询goods表
    goods表 getGoods()方法内joinwith回调 可以查询merchant加盟商表

  • 相关阅读:
    PHP深入浅出之命名空间(Namespace)的使用详解
    函数func_get_args详解
    验证码封装类
    PHP中SESSION自定义会话管理器
    网页开发常见问题总结
    mysql远程连接只显示部分数据库问题
    认识和学习bash
    IPv6地址格式示例及IPv6与IPv4的区别分析
    用HTTP核心模块配置一个静态Web服务器
    Nginx服务项的基本配置
  • 原文地址:https://www.cnblogs.com/jimz/p/7879849.html
Copyright © 2011-2022 走看看