@@ -142,9 +142,9 @@ public static function queryCondition(array $instances, mixed $value, array &$pa
142142 if (isset ($ value [0 ]) && in_array ($ value [0 ], [':notempty: ' , ':empty: ' , 'not :empty: ' ])) {
143143 $ emptyCondition = array_shift ($ value );
144144 if (in_array ($ emptyCondition , [':notempty: ' , 'not :empty: ' ])) {
145- $ conditions [] = static ::existsQueryCondition ($ field );
145+ $ conditions [] = static ::existsQueryCondition ($ field, instances: $ instances );
146146 } else {
147- $ conditions [] = ['not ' , static ::existsQueryCondition ($ field )];
147+ $ conditions [] = ['not ' , static ::existsQueryCondition ($ field, instances: $ instances )];
148148 }
149149 }
150150
@@ -181,10 +181,28 @@ public static function queryCondition(array $instances, mixed $value, array &$pa
181181 * @return array
182182 * @since 5.2.0
183183 */
184- public static function existsQueryCondition (self $ field , bool $ enabledOnly = true , bool $ inTargetSiteOnly = true ): array
184+ public static function existsQueryCondition (self $ field , bool $ enabledOnly = true , bool $ inTargetSiteOnly = true , array $ instances = [] ): array
185185 {
186186 $ ns = sprintf ('%s_%s ' , $ field ->handle , StringHelper::randomString (5 ));
187187
188+ if (count ($ instances ) > 1 ) {
189+ $ instanceQuery = [];
190+ foreach ($ instances as $ instance ) {
191+ $ instanceQuery [] = [
192+ 'and ' ,
193+ ['not ' , [$ instance ->getValueSql () => null ]],
194+ ['not ' , [$ instance ->getValueSql () => '[] ' ]],
195+ ];
196+ }
197+ array_unshift ($ instanceQuery , 'or ' );
198+ } else {
199+ $ instanceQuery = [
200+ 'and ' ,
201+ ['not ' , [$ field ->getValueSql () => null ]],
202+ ['not ' , [$ field ->getValueSql () => '[] ' ]],
203+ ];
204+ }
205+
188206 $ query = (new Query ())
189207 ->from (["relations_ $ ns " => DbTable::RELATIONS ])
190208 ->innerJoin (["elements_ $ ns " => DbTable::ELEMENTS ], "[[elements_ $ ns.id]] = [[relations_ $ ns.targetId]] " )
@@ -193,8 +211,10 @@ public static function existsQueryCondition(self $field, bool $enabledOnly = tru
193211 'and ' ,
194212 "[[relations_ $ ns.sourceId]] = [[elements.id]] " ,
195213 [
196- "relations_ $ ns.fieldId " => $ field ->id ,
197- "elements_ $ ns.dateDeleted " => null ,
214+ 'and ' ,
215+ ["relations_ $ ns.fieldId " => $ field ->id ],
216+ $ instanceQuery ,
217+ ["elements_ $ ns.dateDeleted " => null ],
198218 ],
199219 [
200220 'or ' ,
0 commit comments