Reputation: 4508
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
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