0


I am developing REST API in Yii2. In search query i want to achieve this

 WHERE ((`variant_name` LIKE '%size%' AND `variant_value` 
 LIKE '%12%') OR (`variant_name` LIKE '%color%' AND `variant_value` LIKE '%12%'))

the variant_name and variant_value are an array sent in the URL. The corrsponding Yii2 code i am using right now is as follows

$query->andFilterWhere(['or',
['or like', 'pvo.variant_name', $this->variant_name],
['or like', 'pvo.variant_value', $this->variant_value]])
 ->groupBy(['pvo.product_variant_id'])
 ->having(['count(product_variant_id)' => count($this->variant_name)]);
        ;

Which is generating the following SQL

AND ((`variant_name` LIKE '%size%' OR .`variant_name` LIKE '%color%')
 OR (`variant_value` LIKE '%13%' OR `variant_value` LIKE '%56%')))

But i want varaint_name[0] and varaint_value[0] in single bracket having AND condition with varaint_name[1] and varaint_value[1] like mentioned above. Kindly guide me how should i go about it in Yii2?

Update 1 Sample URL http://localhost:8080/online-malls/api/web/v1/products?expand=product_variant_options&variant_name[0]=size&variant_value[0]=13&variant_name[1]=color&variant_value[1]=56

3
  • in Which wya the variant_name and variant_value are sent in the url ? .. please update your question adding sample of your url or of the qay you forming the param for the url Commented Dec 24, 2016 at 12:47
  • @scaisEdge Thanks for the response . I have updated the question Commented Dec 24, 2016 at 13:50
  • 1
    I have posted and answer hope i what you are looking for Commented Dec 24, 2016 at 13:58

1 Answer 1

1

If you are using an array in get then you should use the array value in param eg:

  $query->andFilterWhere(['or',
    ['or like', 'pvo.variant_name', $this->variant_name[0]],
    ['or like', 'pvo.variant_value', $this->variant_value[0]], 
    ['or like', 'pvo.variant_name', $this->variant_name[1]],
    ['or like', 'pvo.variant_value', $this->variant_value[1]],
    ])
     ->groupBy(['pvo.product_variant_id'])
     ->having(['count(product_variant_id)' => count($this->variant_name)]);
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Thanks for the answer. But what if i don't know in advance length of an array? Do i need to loop through this? or is there any other workaround.
For me the simple way is the use of a loop for prepare the porper filter condition ..
Thanks again. One more thing the fourth OR operator is creating a syntax error . Could you please fix it too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.