编写ActiveQuery以根据id和父ID获取父行和子行?

时间:2016-08-17 19:54:29

标签: php mysql activerecord yii2

我有一个表'order'看起来有点像这样:

order_id    parent_id    item
14056       14054        Cheese
14055       14054        Butter
14054       NULL         Bread

现在,当我有订单id = 14055时,我想返回所有相关的行。如果order_id = 14056或14054,则相同。

1 个答案:

答案 0 :(得分:2)

我认为这会奏效:

解决方案1 ​​

定义Orders模型中的关系:

/**
 * @return \yii\db\ActiveQuery
 */
public function getParent()
{
    return $this->hasOne(Orders::className(), ['order_id' => 'parent_id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getOrders()
{
    return $this->hasMany(Orders::className(), ['parent_id' => 'order_id']);
}

然后你可以运行以下内容:

$data = Orders::find()
        ->from('orders orders')
        ->joinWith('parent parent')
        ->where(['parent.order_id' => 14054])
        ->all();

生成的SQL是:

SELECT `orders`.* 
FROM `orders` `orders` 
LEFT JOIN `orders` parent
ON `orders`.`parent_id` = `parent`.`order_id` 
WHERE `parent`.`order_id`= 14054

解决方案2

如果没有关系,你可以这样:

$sub_query = Orders::find()
        ->select(['order_id'])
        ->where(['order_id' => 14054]);
$query = Orders::find()->where(['in', 'parent_id', $sub_query]);
$data = $query->all();

解决方案3

使用嵌套查询:

$sub_query = Orders::find()
        ->select(['order_id'])
        ->where(['order_id' => 14054]);
$query = Orders::find()
        ->from('orders orders');
$query->innerJoin(['parent' => $sub_query], 'orders.parent_id = parent.order_id');
$data = $query->all();

生成的SQL如下:

SELECT `orders1`.* 
FROM `orders` `orders1` 
INNER JOIN (
    SELECT `order_id` FROM `orders` WHERE `order_id` = 14054
) `parent` 
ON orders.parent_id = parent.order_id

解决方案4

我认为以下内容也会起作用:

inverted模型中定义新的Orders关系:

public function getOrders1()
    {
        return $this->hasMany(Orders::className(), ['parent_id' => 'order_id'])->inverseOf('orders');
    }

现在运行查询:

$data = Orders::find()
        ->with(['orders1'])
        ->all();

关于倒置关系的更多信息here