Yii2 hasMany user condition

I have a sql condidtion SELECT * FROM (SELECT * FROM Prices WHERE aliasId = :aliasId order by id desc) p1 group by p1.currencyand I'm trying to use it in a hasMany statement.

   $q = $this->hasMany(Prices::className(), ['aliasId' => 'id']);
   $db = \Yii::$app->db;
   $query = $db
            ->createCommand('SELECT * FROM (SELECT * FROM Prices WHERE aliasId = :aliasId order by id desc) p1 group by p1.currency')
            ->bindValue(':aliasId', $this->id);
        $query->prepare(true);
        $q->sql = $query->getRawSql();
        return $q;

But $this->idempty when hasMany calls. Is there a way to link a custom array of requests and links?

UPDATE I know the reason is $this->idempty because I use Prices::find()>with('prices')in my controller, so Yii creates a request for all price lists. hasManyjust adds addWhere('in', $key, $value)to the empty request from the parameter $link, I'm trying to override its request, but I can’t.

+4
source share
2 answers

$this->id PriceAlias db - , getPrices() , .

, $this->id != null $this->isNewRecord == false, , null, .

1: , , Prices::find()>with('prices') WHERE ... IN (...), hasMany addWhere, ActiveRecord. :

$this->hasMany(Prices::className(), ['aliasId' => 'id'])
// generates: SELECT * FROM `prices` WHERE `aliasId` = :id

, getPrices() .

, ? $q->sql = $query->getRawSql();, $q->sql SELECT * FROM (SELECT * FROM Prices WHERE aliasId = :aliasId order by id desc) p1 group by p1.currency?

2: . - Prices::find()->with() sql, , , .

find()->with() , .

0

:

$subQuery = (new Query())->select('id')->from('user')->where('status=1');

// SELECT * FROM (SELECT `id` FROM `user` WHERE status=1) u 
$query->from(['u' => $subQuery]);

:

$subQuery = (new Query())->select('*')->from('Prices')->where('aliasId = :aliasId', ['aliasId'=>$aliasId])->orderBy('id');
$query->from(['p1' => $subQuery])->groupBy('p1.currency');
0

All Articles