table alias in search model

Model MyModel has this relation


public function getCreatedBy()

    {        

        return $this->hasOne(User::className(), ['id' => 'created_by'])

        ->from(User::tablename().' user1');

    }


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getUpdatedBy()

    {

        return $this->hasOne(User::className(), ['id' => 'updated_by'])

        ->from(User::tablename().' user2');

    }

In MyModelSearch i do this


->andFilterWhere(['like', User::tableName().'1.username', $this->createdByuser])

resulting in sql error

because my code


User::tableName().'1.username'

intended to create string

user1.username

but it create string

user1.username

My current solution is write the table alias manually


->andFilterWhere(['like', 'user1.username', $this->createdByuser])

Any other solution?

Thanks

Hi,

To understand the background of your problem,

please read "quoting table and column names" in the guide:

http://www.yiiframework.com/doc-2.0/guide-db-dao.html#quoting-table-and-column-names

ONE solution could be:

When you are sure that your DB (MySQL?) will never change in that application,

you COULD do in your user Model:




public static function tableName()

{

    // original is something like: 

    // return '{{user}}'

    

    // use this to avoid the `` being created automatically.

    return 'user';

}



Another solution could be - for example - to return different names:




public static function tableName($situation=null)

{

    // default

    if($situation === null){

        return '{{user}}';

    }

    // specific customization to your needs

    if($situation == "custom"){

        return {{user1}};

    }

}



Then you could call it in your search like:




User::tableName("custom")



Regards

Understood, thx for the tips. I use user model extend from dektrium yii2 user module. That quote come from the parent model. :D