AR find methods... implicit where parameter requested?!?!?

Oh guys, i’m going crazy…

After several months of Yii development, complex Active Record structures, etc…etc… I realized that I did not understand anything…

Following my problem.

When I do a findAll on AR with scopes like this:


$dealeravailabilityproducts = ProductAvailability::model()->dealeravailability($data->id)->findAll();

I get this error:


CDbCommand ha riportato un errore nell'esecuzione della query SQL: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AND (iddealer = 2)' at line 1. The SQL statement executed was: SELECT * FROM `md_productavailability` `t` WHERE (idproduct = ) AND (iddealer = 2)

WTF?!??

As you can see the error is very simple: generated query asks for idproduct parameters in WHERE clause. But… I did not have defined this parameter anywhere in ProductAvailability AR class, nor in parameterized named scope method!!!




// Parameterized named scopes

    // Get product availability

    public function dealeravailability($iddealer)

    {


        $this->getDbCriteria()->mergeWith(array(

            'condition'=>'iddealer = ' . $iddealer,

        ));


        return $this;

    }



The same occurs if I change call AR query:


$dealeravailabilityproducts = ProductAvailability::model()->findAll('iddealer = ' . $data->id);

HELP! :unsure:

I found the problem. There was another parameterized named scope named like the the AR class:




// Get product availability

//    public function productavailability($idproduct)

//    {

//

//        $this->getDbCriteria()->mergeWith(array(

//            'condition'=>'idproduct = ' . $idproduct,

//        ));

//

//        return $this;

//    }



But I still no understand why I get this conflict. ???

If it’s a relational query or search, then probably your problem is with the table aliases. When using scopes, make sure you use the getTableAlias() function.

Try to change your code like this:


    // Parameterized named scopes

    // Get product availability

    public function dealeravailability($iddealer)

    {

        $alias = $this->getTableAlias();  //in defaultScope use getTableAlias(false,false)

        $criteria = new CDbCriteria;

        $criteria->compare("$alias.iddealer", $iddealer);

        $this->getDbCriteria()->mergeWith($criteria);


        return $this;

    }

Let me know if it helps. Also as a good tip: try to avoid the use of $criteria->condition in scopes.