yii with

with 用法
一对多
在 user 模型表中定义

public function getOrders() {
    return $this->hasMany(Orders::className(), ['user_id' => 'id']);
}

在控制器中调用

$orders = User::findOne(1)->orders; 

//或者, 最好这样调用

$orders = User::find()->with('orders')->asArray()->all();

// 执行语句

 $user_id = select * from user where user_id = 2;
            select * from orders where user_id = $user_id;

中间关联表查询,多对多

Orders表中定义

public function getGoods() {
    return $this->hasMany(Goods::className(), ['goods_id' => 'goods_id'])
                ->viaTable("orders_goods", ['orders_id' => 'id']);
}
$orders = Orders::find()->where(['id' => [2,6]])->with('goods')->asArray()->all();

先执行SQL语句 $orders = select * from orders where orders_id in (2, 6);
//之后获取$orders_id数组

  $orders_goods = select * from orders_goods where orders_id in ($orders_id);
              //从$orders_goods 获取 $goods_id数组; 对应viaTable order_goods

              $goods = select * from goods where goods_id in ($goods_id);
              //对应hasMany Goods::className;

你可能感兴趣的:(yii)