Working with relationships
ActiveRecord provides us with skills to work with relationships between database tables. Yii2 employs two methods to establish the relationship between the current and other ActiveRecord classes: hasOne
and hasMany
, which return an ActiveQuery based on the multiplicity of the relationship.
The first method hasOne()
returns at most one related record that matches the criteria set by this relationship, and hasMany()
returns multiple related records that match the criteria set by this relationship.
Both methods require that the first parameter is the class name of the related ActiveRecord and that the second parameter is the pair of primary keys that are involved in the relationship: the first key is relative to a foreign ActiveRecord and the second key is related to the current ActiveRecord.
Usually, hasOne()
and hasMany()
are accessed from properties that identify which object (or objects) will be returned.
The method in this example is:
class Room extends ActiveRecord...