使用via或viaTable关系从关系生成mysql查询

问题描述 投票:1回答:1

考虑下面的例子......

class Customers extends ActiveRecord
{
    public function getOrders()
    {
        return $this->hasMany(Orders::className(), ['customer_id' => 'id']);
    }
    public function getOrderItems()
    {
        return $this->hasMany(OrderItems::className(), ['order_id' => 'id'])
                    ->via('orders');
    }
}

我如何从getOrderItems()关系生成以下任何一个查询

SELECT * FROM `order-items`
LEFT JOIN `orders` ON `orders`.`id` = `order-items`.`order_id`
LEFT JOIN `customers` ON `customer`.`id` = `orders`.`customer_id`

要么

SELECT `order-items`.* FROM `order-items`,`orders`,`customers`
WHERE `customer`.`id` = `orders`.`customer_id` AND `orders`.`id` = `order-items`.`order_id`

要么

SELECT * FROM `order-items` WHERE `order_id` IN(
    SELECT * FROM `orders` WHERE `customer_id` IN(
        SELECT * FROM `customers`
    )
)

我使用以下代码来执行此操作。

$customers = Customers::findAll();
$query = $customers[0]->getOrderItems()->createCommand()->rawSql;

但它只会产生

SELECT * FROM `order-items`

该怎么办...???

yii yii2 yii2-advanced-app
1个回答
1
投票

用这个 :

$q = Customers::findAll()->innerJoinWith('orderItems')->createCommand()->rawSql;

你必须使用这样的关系名称而不是函数

© www.soinside.com 2019 - 2024. All rights reserved.