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加盟商表

  • 相关阅读:
    Python Revisited Day 13 (正则表达式)
    Python Revisited Day 06 (面向对象程序设计)
    Python Revisited (变量)
    Python Revisited Day 05(模块)
    Python Revisited Day 04 (控制结构与函数)
    Python Revisited Day 03 (组合数据类型)
    Numpy
    Python Revisited Day 01
    Python3使用openpyxl读写Excel文件
    Python3操作YAML文件
  • 原文地址:https://www.cnblogs.com/jimz/p/7879849.html
Copyright © 2011-2022 走看看