P
P
Petr Fronin2016-02-26 13:18:41
Yii
Petr Fronin, 2016-02-26 13:18:41

Yii2 how to get data from a table with relationships?

There are 2 tables (users and contacts) interconnected. Users (id, ...) - information about the user Contacts (id, my_id, contact_id) - who added whom to his contacts
In the users model, it is written:

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

The Contacts model says:
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 works out and returns 1 my first contact, but it is necessary to get all my contacts, logically I write like this:
$qwe = Contacts::findAll(['my_id' => 1]);
$contacts = $qwe->getUser()->all();

but then an error occurs: Call to a member function getUser() on array
What's wrong? How to get all my contacts?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Bukharev, 2016-02-26
@evgenybuckharev

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

If I understand correctly, then you are trying to select all contacts here, then select the user to whom all contacts belong, and again select all contacts from this user.
The error says that you are trying to request the getUser() method from the array returned by the Contacts::findAll(['my_id' => 1]) method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question