首页 > 技术文章 > YII 多表联查 纵表

jimz 2017-11-22 16:28 原文

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

推荐阅读