>我有表属性和property_has_feature
property_has_feature表如下所示。
+-------------+--------------+
| property_id | feature_code |
+-------------+--------------+
| 111 | PENT |
| 122 | GREEN |
| 122 | HFLO |
| 123 | CCAR |
| 111 | CCAR |
| 111 | XBLKV |
| 122 | MFLO |
| 122 | HFLO |
| 111 | BILL |
| 122 | CCAR |
+-------------+--------------+
我想要具有一组功能的属性列表。
例如,我想要具有PENT,CCAR和BILL功能的物业。这应该给我id 为 111 的属性,因为它与提到的所有 3 个功能一样。
我尝试了以下方法,
$featureCodes = ['PENT', 'CCAR', 'BILL'];
$query = Property::find()
->where(['status'=> '1'])
->joinWith('propertyHasFeatures')
->andWhere(['property_has_feature.feature_code'=>$featureCodes]);
但这不会给出所需的结果,而是返回至少在数组中指定的特征上具有的所有属性。
如何编写用于获取具有所有 give 功能的属性的活动查询。
这就是答案。这有点棘手,你不会用一个简单的IN子句得到它。这将返回属性,即使该属性具有列表中的功能之一。我们需要的是具有给定数组中所有特征的属性。
$featureCodes = ['PENT', 'CCAR', 'BILL'];
$query = Property::find()
->where(['status'=> '1'])
->joinWith('propertyHasFeatures')
->andWhere(['property_has_feature.feature_code'=>$featureCodes])
->groupBy('property.id')
->having(' count(distinct property_has_feature.feature_code) = '.count($featureCodes));
>$featureCodes是一个数组,所以你必须在 IN 子句中传递它
将 andwhere 条件更改为
$featureCodes = ['PENT', 'CCAR', 'BILL'];
$query = Property::find()
->where(['status'=> '1'])
->joinWith('propertyHasFeatures')
->andWhere(['IN','property_has_feature.feature_code',$featureCodes]);