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

时间:2017-12-27 10:58:02

标签: yii yii2 yii2-advanced-app

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

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`

OR

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

OR

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`

怎么做...... ???

1 个答案:

答案 0 :(得分:1)

使用它:

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

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