简体   繁体   中英

How can I make an alias on yii SQL statement using relationships?

I'm trying to associate two tables using the following code on Yii:

$this->stocks= $stocks->find()->select(['id', 'type.name'])->joinWith('stockType type')->where(['fk_product' => $productId, 'fk_product_type' => 'type.id'])->all();

The problem is: I want the stocks ID and i'm geting an error saying the ID is ambiguous:

1052 Column 'id' in field list is ambiguous

So, how can I name the table $stocks or make it an alias so that I can remove the ambiguity?

Thanks!

Assuming that StocksModel is the prototype-class of $stocks , you can do as below.

$socksTableName = StocksModel::tableName();

$this->stocks= StocksModel::find()
    ->select([$socksTableName . '.id', 'type.name'])
    ->joinWith('stockType type')
    ->where([
        'fk_product' => $productId,
        'fk_product_type' => 'type.id'
    ])
    ->all();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM