我喜欢在两个相关的 Yii2 模型
上选择特定的相关数据。两个模型都陷入1:n
关系。关系运转良好!
订购型号:
- @property 整数 $id
订单模型关系定义:
/**
* @return \yii\db\ActiveQuery
*/
public function getTimeCaptures()
{
return $this->hasMany(TimeCapture::className(), ['orderId' => 'id']);
}
timeCapture模型:
- @property 整数 $id
- @property 整数 $orderId
- @property string $date(MySQL-DB 中的
Datetime
)
我喜欢获取特定日期之间具有相关 timeCaptures
的所有订单
。以下语句将为我提供所有 timeCaptures
。看起来 andWhere
子句不起作用!
/**
* Build query
*/
$orders = Order::find()
->joinWith('timeCaptures')
->andWhere([
'>=',
'timeCapture.date',
$startDateSearch->format('Y-m-d H:i:s')
])
->andWhere([
'<=',
'timeCapture.date',
$endDateSearch->format('Y-m-d H:i:s')
])->all();
这是 $orders->createCommand()->getRawSql()
的原始 SQL 输出:
SELECT `order`.*
FROM `order`
LEFT JOIN `timeCapture` ON `order`.`id` = `timeCapture`.`orderId`
WHERE (`timeCapture`.`date` >= '2017-02-01 00:00:00')
AND (`timeCapture`.`date` <= '2017-02-28 00:00:00')
请提供使用 Yii2 active records 的答案。提前致谢。
最佳答案
如果我没猜错的话,这就是您正在寻找的:
$startDateSearch = new DateTime('2017-02-10');
$endDateSearch = new DateTime('2017-02-17');
$orders = Order::find()->with([
'timeCaptures' => function (\yii\db\ActiveQuery $query) use($startDateSearch, $endDateSearch) {
$query
->andWhere([
'>=',
'timeCapture.date',
$startDateSearch->format('Y-m-d H:i:s')
])
->andWhere([
'<=',
'timeCapture.date',
$endDateSearch->format('Y-m-d H:i:s')
]);
},
])->all();
var_dump($orders);
抱歉这么晚才回复
关于php - Yii2 模型 - activerecord join With + andWhere 日期选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055113/