phpyii2

What are the rules for interpreting "logically ambiguous" queries in Yii2?


In Yii2, you can add clauses to queries such as:

Product::find()
->where(['name' => 'MyProd'])
->andWhere(['type' => 'Toy'])
->orWhere(['category' => 'MyCat'])
->andWhere(['location' => 'MyLoc'])

How is this interpreted? Is it that it finds products that

  1. are called 'MyProd' and have type 'Toy'

or

  1. are in category 'MyCat' and have location 'MyLoc' ?

Is it that it finds products which :

  1. are called 'My Prod'

and

  1. have Type 'Toy' or are in category 'MyCat'

and

  1. have location 'MyLoc'?

Is it something else entirely? Is there a general rule that can be described easily for how such "logically ambiguous" queries are interpreted?


Solution

  • Neither of your interpretation is correct.

    The correct interpretation would be that it finds products that:

     1. Have location "MyLoc"
       and 
     2.1. Have category "MyCat"
         or
     2.2. Have name "MyProd" and type "Type"
    

    This is because when andWhere() and orWhere() methods are called, they take existing conditions and add new condition to existing conditions using and/or.

    So, if you rewrite your methods call into single complex array condition you will get:

    [
        'and',
        [
            'or',
            [
                'and',
                ['name' => 'MyProd'],
                ['type' => 'Toy'],
            ],
            ['category' => 'MyCat'],
        ],
        ['location' => 'MyLoc'],
    ]
    

    Translated into MySQL condition you will get:

    ((name = "MyProd" AND type = "Toy") OR category = 'MyCat') AND location = 'MyLoc'