I have a table 'orders' that looks a bit like this:
order_id parent_id item
14056 14054 Cheese
14055 14054 Butter
14054 NULL Bread
Now, when I have the order id = 14055 I want to return all rows that are related. Same if order_id = 14056 or 14054.
I think this will work:
Solution 1
Define the relations in your Orders
model:
/**
* @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']);
}
And then you can run the following:
$data = Orders::find()
->from('orders orders')
->joinWith('parent parent')
->where(['parent.order_id' => 14054])
->all();
The SQL which is produced is:
SELECT `orders`.*
FROM `orders` `orders`
LEFT JOIN `orders` parent
ON `orders`.`parent_id` = `parent`.`order_id`
WHERE `parent`.`order_id`= 14054
Solution 2
Without relations you can you something like this:
$sub_query = Orders::find()
->select(['order_id'])
->where(['order_id' => 14054]);
$query = Orders::find()->where(['in', 'parent_id', $sub_query]);
$data = $query->all();
Solution 3
Using nested query:
$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();
The produced SQL is the following:
SELECT `orders1`.*
FROM `orders` `orders1`
INNER JOIN (
SELECT `order_id` FROM `orders` WHERE `order_id` = 14054
) `parent`
ON orders.parent_id = parent.order_id
Solution 4
I think that also the following will work too:
Define the new inverted
relation in Orders
model:
public function getOrders1()
{
return $this->hasMany(Orders::className(), ['parent_id' => 'order_id'])->inverseOf('orders');
}
Now run the query:
$data = Orders::find()
->with(['orders1'])
->all();
More about the inverted relations here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.