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:
Please show me useful aspect of this feature: with()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With