David
David

Reputation: 4508

SQL Request from several tables in Yii2

I have 2 tables. and $id variable with id of A table

$A_data= A::find()
    ->where(['id' => $id])
    ->one();
$B_data= B::find()
    ->where(['id' => $A_data->B_id])
    ->one();
echo $B_data->name;

This code takes id and gets line from A table, then taking B_id from that line gets line from B table. Then I print out data from B table.

How can I do this with one single request ? not asking tables for data one after another ?

Upvotes: 0

Views: 90

Answers (1)

soju
soju

Reputation: 25312

You should have the following relation in your A model, e.g. :

public function getB()
{
    return $this->hasOne(B::className(), ['id' => 'B_id']);
}

And your code could be :

$A_data = A::find()->where(['id'=>$id])->one();
echo $A_data->B->name;

PS: there will be two sql requests for this (lazy or eager).

Upvotes: 1

Related Questions