Search code examples
phpyii2foreign-keys

In Yii2, is it possible to get the unique objects in a hasMany relation via another hasMany relation?


Say I have an Order model which has some associated Product models, so there's a relation in Order:

    public function getProducts() {
        return $this->hasMany(Product::class, ['id' => 'id_product']);
    }

A product Product can be associated to multiple acquisitors. So Product has a relation:

   public function getAcquisitors() {
        return $this->hasMany(Acquisitor::class, ['id' => 'id_acquisitor']);
    }

Now, is it possible to write a relation in Order which returns an ActiveQuery with unique Acquisitors? If in Order I do:

public function getAcquisitors() {
        return $this->hasMany(Acquisitor::class, ['id' => 'id_acquisitor'])->via('products');
    }

isn't this going to return duplicate Acquisitors? Is it possible to make them unique?


Solution

  • The relation acquisitors won't contain duplicate records. That's because Yii loads related models independently with query like this:

    SELECT FROM <related table> WHERE <key> IN (<list of keys>)
    

    When loading relation that is defined as "via" then it first load the models in "via" relation then use them to load models in dependent relation. Both loading is done using query similar to one mentioned above.