There are 2 tables (users and contacts) related. Users (id, ...) - information about the user Contacts (id, my_id, contact_id) - who added to whom to his contacts

In the users model it is written:

public function getContact() { return $this->hasMany(Contacts::className(), ['contact_id' => 'id']); } 

In the Contacts model it is written:

  public function getUser() { return $this->hasOne(User::className(), ['id' => 'contact_id']); } 

In SiteController we request my contacts:

 $qwe = Contacts::findOne(['my_id' => 1]); $contacts = $qwe->getUser()->all(); 

the code executes and returns 1 my first contact, but I need to get all my contacts, logically I write this:

 $qwe = Contacts::findAll(['my_id' => 1]); $contacts = $qwe->getUser()->all(); 

but here the error takes off: Call to a member function getUser () on array

What's wrong? How to get all my contacts?

    2 answers 2

    In Yii2, the findAll method returns an array of ActiveRecord objects, as written in the documentation

    Array of instances of the array.

    The array can be brute force `

     foreach($qwe as $item) { $linkedData = $item->getUser()->all(); // Потом делаете то, что вам надо } 

      Your connection getUser should have hasMany apparently.

      • Tried and so, the result is the same: error - Alexey
      • Then, logically, you need to request contacts from the user model, and not from the contact model (s). In the user class, add the link return $this->hasMany(User::className(), ['id' => 'contact_id'])->viaTable('contacts', ['my_id' => 'id']); - Ivan Samsonov