0

users

ID | customerID | <others>

userTemplates

ID | userID | productCode

templates

ID | customerID | productCode | <others>

Im trying to find a nice solution to get all templates that are assigned to a given user based on the prodCode in the userTemplates table.

The product codes need to contain a wild card % so would be like this P.0100.% or %.0100.%

I have done this so far:

$usersTemplates = ArrayHelper::map(userTemplates::find()->where("userID = ".Yii::$app->user->identity->ID."")->all(),'ID','productCode');

$templates = new Query;
$templates->from('templates')
          ->where("customerID = ".Yii::$app->user->identity->customer->ID."")
          ->andWhere("disabled = 0")
          ->andWhere("approved = 1");

foreach($usersTemplates as $prodCode){
    $templates->andWhere("productCode LIKE '%".$prodCode."%'");
}

but i end up with this

SELECT * FROM `templates` WHERE ((((customerID = 1) AND (disabled = 0)) AND (approved = 1)) AND (productCode LIKE '%TESTWP%')) AND (productCode LIKE '%P.0100.0001%')

which is almost there but this bit:

AND (productCode LIKE '%TESTWP%')) AND (productCode LIKE '%P.0100.0001%')

needs to be:

AND ((productCode LIKE '%TESTWP%')) OR (productCode LIKE '%P.0100.0001%'))

Im sure there might be a better way of getting the list of templates.

Thanks in advance

1 Answer 1

1

when you have a complex query a simple solution is based on findBySql

$sql = "SELECT * 
  FROM `templates` 
  WHERE ((((customerID = 1) 
  AND (disabled = 0)) 
  AND (approved = 1)) 
  AND ((productCode LIKE '%TESTWP%')) 
  OR (productCode LIKE '%P.0100.0001%'))";

$model = Templates::findBySql($sql)->all(); 
Sign up to request clarification or add additional context in comments.

Comments

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.