Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 find with() - What is it for?

Maybe this question is very simple but I couldn't understand what is with() in yii2 despite I've read couple of articles about it. What does this mean:

$players = PlayersModel::find()->with("countries")->all();

What is this for? In my database (tables are related) on what purpose can it be used:

enter image description here

Please show me useful aspect of this feature: with()

like image 667
Scott Avatar asked Dec 10 '22 11:12

Scott


1 Answers

with() is explained in the Yii 2 Guide.

This method allows to eagerly load the relational data in your query.

In your example there is PlayersModel. I assume there is also ClubsModel that represents data from database table clubs.

Let's say Player belongs to one of the Clubs. There should be defined relation between PlayersModel and ClubsModel. If it's defined in PlayersModel it could be something like:

public function getClub()
{
    return $this->hasOne(ClubsModel::className(), ['id' => 'id_club']);
}

So now there is relation named club. Each time you call $model->club (where $model is object of PlayersModel) you get related ClubsModel object.

Now - when you look for specific Player:

$player = PlayersModel::find()->where(['id' => $id])->one();

or (a bit simpler to write):

$player = PlayersModel::findOne($id);

This is one performed SQL query. In next step you want to get the Club of this Player - there is relation already defined so you can call:

$club = $player->club;

But this performes another SQL query - it's called lazy loading.

Let's say you know you need Player data together with his Club data at once - you can use with() to get this:

$player = PlayersModel::find()->where(['id' => $id])->with('club')->one();

It's one SQL query. Now when you call:

$club = $player->club;

There is no need for second query this time because this relational data is already fetched - it's called eager loading.

like image 140
Bizley Avatar answered Dec 29 '22 00:12

Bizley