generate mysql query from relations using via or viaTable relations

时间秒杀一切 提交于 2019-12-11 04:18:34

问题


consider the below example...

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');
    }
}

how i can generate any one of the follwing query from the getOrderItems() relation

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`
    )
)

i use the following code to do this.

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

but it only generates

SELECT * FROM `order-items`

What to do...???


回答1:


use this :

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

you have to use relation name like this not as function



来源:https://stackoverflow.com/questions/47990955/generate-mysql-query-from-relations-using-via-or-viatable-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!