AR scope question

Hi,
I define a new class that extends ActiveQuery with a method myScope() that do something.
So I can write myModel::find()->myScope(). And that’s work correctly.
MyModel has an hasMany() relation with an other model , public function getRelationName() {}
Now the problem is I can’t write myModel::find()->relationName->myScope() because getRelationName() return me an array of ActiveRecord object, It’s not an ActiveQuery object.
It only works if I write myModel::find()->getRelationName()->myScope() but I don’t want call the relation in this way.
Any suggestions?
Thx

can you show your code ?

Could be, that you could change to myScope()->getRelationName

Thx demonking for your replay,
this is my code :

class MyQuery extends ActiveQuery {

//Filter on last record
public function onlyPresent() {

    $this->andOnCondition(['Active => 1']);
   return $this;
         }

}

//Model 1
class Costumers extends ActiveRecord {
//myRelation
public function getAddressColl() {

                     return $this->hasMany(Address::className(), ['Id' => 'Id']);
     
}

}

//View

$x = Costumers::find()->with(‘addressColl’)->where([’=’, ‘Id’, ‘012345’])->one();
$lastAddress = $x->addressColl->onlyPresent()->all();
//-------------------------
The code upper doesn’t work…
Please, explain me better what about your suggestion.
Thx
Roberto

hi,

first things first: both, your Costumers and your relation uses the same Col-Name (“Id”) as Primary Key. You should add a prefix, e.g. tableName().

Then, you try to call a Method “all()” on the Address model.
When working with AR-Relations in Yii a call to

$x->addressColl returns a Array with AR’s models.

What you want is a instance of ActiveQuery. Please use
$x->getAddressColl()->onlyPresent()->all() to add the Scope to your ActiveQuery.

refer to docs

Note: While this concept looks similar to the object property feature, there is an important difference. For normal object properties the property value is of the same type as the defining getter method. A relation method however returns an yii\db\ActiveQuery instance, while accessing a relation property will either return a yii\db\ActiveRecord instance or an array of these.

$customer->orders; // is an array of `Order` objects
$customer->getOrders(); // returns an ActiveQuery instance