Yii 2.0 hasMany

In our last post, you learned how to join two tables using joinWith() and using hasOne when declaring your relation. In this post I want to tell you the difference between hasOne and hasMany.
In our last post, you learned how to join two tables using joinWith() and using hasOne when declaring your relation.
In this post I want to tell you the difference between hasOne and hasMany.
As an example, we have two tables. One is called 'Person' and the other is called 'Telephone'. 'Person' attributes are, 'pid, name, type' and our primary key is 'pid'. 'Telephone' attributes are 'phone_id,pid,no' and our primary key is 'phone_id' and 'pid' is a foreign key to 'Person'. Imagine each record in 'Person' can have more than one phone number. Now we want to join these two tables. Our standard SQL Query would be,
"Select * From 'Person' LEFT JOIN 'Telephone' on 'Person.pid'='Telephone.pid'"
The relation defined in 'Person' Model which indicates that a record in 'Person' can have more than one record in 'Telephone' is as follows:
public function getPhonenumbers() { return $this->hasMany(Telephone::className(), ['pid' => 'pid']); }
hasMany shows that a record in 'Person' may have can have more than one record in our related table.
So our query changes to:
\app\models\Person::find()->joinWith('phonenumbers')->all();
This query brings all records in 'Person' joined with 'Telephone' using LEFT JOIN on their pids.