Model Relationships

模型关系(Relationships between Models)

有四种关系类型:1对1,1对多,多对1,多对多。关系可以是单向或者双向的,每个关系可以是简单的(一个1对1的模型)也可以是复杂的(1组模型)。 The model manager manages foreign key constraints for these relationships, the definition of these helps referential integrity as well as easy and fast access of related records to a model. Through the implementation of relations, it is easy to access data in related models from each record in a uniform way.

单向关系(Unidirectional relationships)

Unidirectional relations are those that are generated in relation to one another but not vice versa.

双向关系(Bidirectional relations)

The bidirectional relations build relationships in both models and each model defines the inverse relationship of the other.

定义关系(Defining relationships)

In Phalcon, relationships must be defined in the initialize() method of a model. The methods belongsTo(), hasOne(), hasMany() and hasManyToMany() define the relationship between one or more fields from the current model to fields in another model. Each of these methods requires 3 parameters: local fields, referenced model, referenced fields.

MethodDescription
hasManyDefines a 1-n relationship
hasOneDefines a 1-1 relationship
belongsToDefines a n-1 relationship
hasManyToManyDefines a n-n relationship

The following schema shows 3 tables whose relations will serve us as an example regarding relationships:

  1. CREATE TABLE `robots` (
  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  3. `name` varchar(70) NOT NULL,
  4. `type` varchar(32) NOT NULL,
  5. `year` int(11) NOT NULL,
  6. PRIMARY KEY (`id`)
  7. );
  8. CREATE TABLE `robots_parts` (
  9. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  10. `robots_id` int(10) NOT NULL,
  11. `parts_id` int(10) NOT NULL,
  12. `created_at` DATE NOT NULL,
  13. PRIMARY KEY (`id`),
  14. KEY `robots_id` (`robots_id`),
  15. KEY `parts_id` (`parts_id`)
  16. );
  17. CREATE TABLE `parts` (
  18. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  19. `name` varchar(70) NOT NULL,
  20. PRIMARY KEY (`id`)
  21. );
  • The model “Robots” has many “RobotsParts”.
  • The model “Parts” has many “RobotsParts”.
  • The model “RobotsParts” belongs to both “Robots” and “Parts” models as a many-to-one relation.
  • The model “Robots” has a relation many-to-many to “Parts” through “RobotsParts”.

Check the EER diagram to understand better the relations:

../_images/eer-1.png

The models with their relations could be implemented as follows:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public function initialize()
  9. {
  10. $this->hasMany(
  11. "id",
  12. "RobotsParts",
  13. "robots_id"
  14. );
  15. }
  16. }
  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Parts extends Model
  4. {
  5. public $id;
  6. public $name;
  7. public function initialize()
  8. {
  9. $this->hasMany(
  10. "id",
  11. "RobotsParts",
  12. "parts_id"
  13. );
  14. }
  15. }
  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class RobotsParts extends Model
  4. {
  5. public $id;
  6. public $robots_id;
  7. public $parts_id;
  8. public function initialize()
  9. {
  10. $this->belongsTo(
  11. "robots_id",
  12. "Store\\Toys\\Robots",
  13. "id"
  14. );
  15. $this->belongsTo(
  16. "parts_id",
  17. "Parts",
  18. "id"
  19. );
  20. }
  21. }

The first parameter indicates the field of the local model used in the relationship; the second indicates the name of the referenced model and the third the field name in the referenced model. You could also use arrays to define multiple fields in the relationship.

Many to many relationships require 3 models and define the attributes involved in the relationship:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public function initialize()
  9. {
  10. $this->hasManyToMany(
  11. "id",
  12. "RobotsParts",
  13. "robots_id", "parts_id",
  14. "Parts",
  15. "id"
  16. );
  17. }
  18. }

使用关系(Taking advantage of relationships)

When explicitly defining the relationships between models, it is easy to find related records for a particular record.

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst(2);
  4. foreach ($robot->robotsParts as $robotPart) {
  5. echo $robotPart->parts->name, "\n";
  6. }

Phalcon uses the magic methods __set/__get/__call to store or retrieve related data using relationships.

By accessing an attribute with the same name as the relationship will retrieve all its related record(s).

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst();
  4. // All the related records in RobotsParts
  5. $robotsParts = $robot->robotsParts;

Also, you can use a magic getter:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst();
  4. // All the related records in RobotsParts
  5. $robotsParts = $robot->getRobotsParts();
  6. // Passing parameters
  7. $robotsParts = $robot->getRobotsParts(
  8. [
  9. "limit" => 5,
  10. ]
  11. );

If the called method has a “get” prefix Phalcon\Mvc\Model will return a findFirst()/find() result. The following example compares retrieving related results with using magic methods and without:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst(2);
  4. // Robots model has a 1-n (hasMany)
  5. // relationship to RobotsParts then
  6. $robotsParts = $robot->robotsParts;
  7. // Only parts that match conditions
  8. $robotsParts = $robot->getRobotsParts(
  9. [
  10. "created_at = :date:",
  11. "bind" => [
  12. "date" => "2015-03-15"
  13. ]
  14. ]
  15. );
  16. $robotPart = RobotsParts::findFirst(1);
  17. // RobotsParts model has a n-1 (belongsTo)
  18. // relationship to RobotsParts then
  19. $robot = $robotPart->robots;

Getting related records manually:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst(2);
  4. // Robots model has a 1-n (hasMany)
  5. // relationship to RobotsParts, then
  6. $robotsParts = RobotsParts::find(
  7. [
  8. "robots_id = :id:",
  9. "bind" => [
  10. "id" => $robot->id,
  11. ]
  12. ]
  13. );
  14. // Only parts that match conditions
  15. $robotsParts = RobotsParts::find(
  16. [
  17. "robots_id = :id: AND created_at = :date:",
  18. "bind" => [
  19. "id" => $robot->id,
  20. "date" => "2015-03-15",
  21. ]
  22. ]
  23. );
  24. $robotPart = RobotsParts::findFirst(1);
  25. // RobotsParts model has a n-1 (belongsTo)
  26. // relationship to RobotsParts then
  27. $robot = Robots::findFirst(
  28. [
  29. "id = :id:",
  30. "bind" => [
  31. "id" => $robotPart->robots_id,
  32. ]
  33. ]
  34. );

The prefix “get” is used to find()/findFirst() related records. Depending on the type of relation it will use find() or findFirst():

TypeDescriptionImplicit Method
Belongs-ToReturns a model instance of the related record directlyfindFirst
Has-OneReturns a model instance of the related record directlyfindFirst
Has-ManyReturns a collection of model instances of the referenced modelfind
Has-Many-to-ManyReturns a collection of model instances of the referenced model, it implicitly does ‘inner joins’ with the involved models(complex query)

You can also use the “count” prefix to return an integer denoting the count of the related records:

  1. <?php
  2. use Store\Toys\Robots;
  3. $robot = Robots::findFirst(2);
  4. echo "The robot has ", $robot->countRobotsParts(), " parts\n";

定义关系(Aliasing Relationships)

To explain better how aliases work, let’s check the following example:

The “robots_similar” table has the function to define what robots are similar to others:

  1. mysql> desc robots_similar;
  2. +-------------------+------------------+------+-----+---------+----------------+
  3. | Field | Type | Null | Key | Default | Extra |
  4. +-------------------+------------------+------+-----+---------+----------------+
  5. | id | int(10) unsigned | NO | PRI | NULL | auto_increment |
  6. | robots_id | int(10) unsigned | NO | MUL | NULL | |
  7. | similar_robots_id | int(10) unsigned | NO | | NULL | |
  8. +-------------------+------------------+------+-----+---------+----------------+
  9. 3 rows in set (0.00 sec)

Both “robots_id” and “similar_robots_id” have a relation to the model Robots:

../_images/eer-2.png

A model that maps this table and its relationships is the following:

  1. <?php
  2. class RobotsSimilar extends Phalcon\Mvc\Model
  3. {
  4. public function initialize()
  5. {
  6. $this->belongsTo(
  7. "robots_id",
  8. "Store\\Toys\\Robots",
  9. "id"
  10. );
  11. $this->belongsTo(
  12. "similar_robots_id",
  13. "Store\\Toys\\Robots",
  14. "id"
  15. );
  16. }
  17. }

Since both relations point to the same model (Robots), obtain the records related to the relationship could not be clear:

  1. <?php
  2. $robotsSimilar = RobotsSimilar::findFirst();
  3. // Returns the related record based on the column (robots_id)
  4. // Also as is a belongsTo it's only returning one record
  5. // but the name 'getRobots' seems to imply that return more than one
  6. $robot = $robotsSimilar->getRobots();
  7. // but, how to get the related record based on the column (similar_robots_id)
  8. // if both relationships have the same name?

The aliases allow us to rename both relationships to solve these problems:

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class RobotsSimilar extends Model
  4. {
  5. public function initialize()
  6. {
  7. $this->belongsTo(
  8. "robots_id",
  9. "Store\\Toys\\Robots",
  10. "id",
  11. [
  12. "alias" => "Robot",
  13. ]
  14. );
  15. $this->belongsTo(
  16. "similar_robots_id",
  17. "Store\\Toys\\Robots",
  18. "id",
  19. [
  20. "alias" => "SimilarRobot",
  21. ]
  22. );
  23. }
  24. }

With the aliasing we can get the related records easily:

  1. <?php
  2. $robotsSimilar = RobotsSimilar::findFirst();
  3. // Returns the related record based on the column (robots_id)
  4. $robot = $robotsSimilar->getRobot();
  5. $robot = $robotsSimilar->robot;
  6. // Returns the related record based on the column (similar_robots_id)
  7. $similarRobot = $robotsSimilar->getSimilarRobot();
  8. $similarRobot = $robotsSimilar->similarRobot;

魔术方法 Getters 对比显示方法(Magic Getters vs. Explicit methods)

Most IDEs and editors with auto-completion capabilities can not infer the correct types when using magic getters, instead of use the magic getters you can optionally define those methods explicitly with the corresponding docblocks helping the IDE to produce a better auto-completion:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. class Robots extends Model
  5. {
  6. public $id;
  7. public $name;
  8. public function initialize()
  9. {
  10. $this->hasMany(
  11. "id",
  12. "RobotsParts",
  13. "robots_id"
  14. );
  15. }
  16. /**
  17. * Return the related "robots parts"
  18. *
  19. * @return \RobotsParts[]
  20. */
  21. public function getRobotsParts($parameters = null)
  22. {
  23. return $this->getRelated("RobotsParts", $parameters);
  24. }
  25. }

虚拟外键(Virtual Foreign Keys)

By default, relationships do not act like database foreign keys, that is, if you try to insert/update a value without having a valid value in the referenced model, Phalcon will not produce a validation message. You can modify this behavior by adding a fourth parameter when defining a relationship.

The RobotsPart model can be changed to demonstrate this feature:

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class RobotsParts extends Model
  4. {
  5. public $id;
  6. public $robots_id;
  7. public $parts_id;
  8. public function initialize()
  9. {
  10. $this->belongsTo(
  11. "robots_id",
  12. "Store\\Toys\\Robots",
  13. "id",
  14. [
  15. "foreignKey" => true
  16. ]
  17. );
  18. $this->belongsTo(
  19. "parts_id",
  20. "Parts",
  21. "id",
  22. [
  23. "foreignKey" => [
  24. "message" => "The part_id does not exist on the Parts model"
  25. ]
  26. ]
  27. );
  28. }
  29. }

If you alter a belongsTo() relationship to act as foreign key, it will validate that the values inserted/updated on those fields have a valid value on the referenced model. Similarly, if a hasMany()/hasOne() is altered it will validate that the records cannot be deleted if that record is used on a referenced model.

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class Parts extends Model
  4. {
  5. public function initialize()
  6. {
  7. $this->hasMany(
  8. "id",
  9. "RobotsParts",
  10. "parts_id",
  11. [
  12. "foreignKey" => [
  13. "message" => "The part cannot be deleted because other robots are using it",
  14. ]
  15. ]
  16. );
  17. }
  18. }

A virtual foreign key can be set up to allow null values as follows:

  1. <?php
  2. use Phalcon\Mvc\Model;
  3. class RobotsParts extends Model
  4. {
  5. public $id;
  6. public $robots_id;
  7. public $parts_id;
  8. public function initialize()
  9. {
  10. $this->belongsTo(
  11. "parts_id",
  12. "Parts",
  13. "id",
  14. [
  15. "foreignKey" => [
  16. "allowNulls" => true,
  17. "message" => "The part_id does not exist on the Parts model",
  18. ]
  19. ]
  20. );
  21. }
  22. }

级联与限制动作(Cascade/Restrict actions)

Relationships that act as virtual foreign keys by default restrict the creation/update/deletion of records to maintain the integrity of data:

  1. <?php
  2. namespace Store\Toys;
  3. use Phalcon\Mvc\Model;
  4. use Phalcon\Mvc\Model\Relation;
  5. class Robots extends Model
  6. {
  7. public $id;
  8. public $name;
  9. public function initialize()
  10. {
  11. $this->hasMany(
  12. "id",
  13. "Parts",
  14. "robots_id",
  15. [
  16. "foreignKey" => [
  17. "action" => Relation::ACTION_CASCADE,
  18. ]
  19. ]
  20. );
  21. }
  22. }

The above code set up to delete all the referenced records (parts) if the master record (robot) is deleted.

存储关系记录(Storing related records)

Magic properties can be used to store a record and its related properties:

  1. <?php
  2. // Create an artist
  3. $artist = new Artists();
  4. $artist->name = "Shinichi Osawa";
  5. $artist->country = "Japan";
  6. // Create an album
  7. $album = new Albums();
  8. $album->name = "The One";
  9. $album->artist = $artist; // Assign the artist
  10. $album->year = 2008;
  11. // Save both records
  12. $album->save();

Saving a record and its related records in a has-many relation:

  1. <?php
  2. // Get an existing artist
  3. $artist = Artists::findFirst(
  4. "name = 'Shinichi Osawa'"
  5. );
  6. // Create an album
  7. $album = new Albums();
  8. $album->name = "The One";
  9. $album->artist = $artist;
  10. $songs = [];
  11. // Create a first song
  12. $songs[0] = new Songs();
  13. $songs[0]->name = "Star Guitar";
  14. $songs[0]->duration = "5:54";
  15. // Create a second song
  16. $songs[1] = new Songs();
  17. $songs[1]->name = "Last Days";
  18. $songs[1]->duration = "4:29";
  19. // Assign the songs array
  20. $album->songs = $songs;
  21. // Save the album + its songs
  22. $album->save();

Saving the album and the artist at the same time implicitly makes use of a transaction so if anything goes wrong with saving the related records, the parent will not be saved either. Messages are passed back to the user for information regarding any errors.

Note: Adding related entities by overloading the following methods is not possible:

  • Phalcon\Mvc\Model::beforeSave()
  • Phalcon\Mvc\Model::beforeCreate()
  • Phalcon\Mvc\Model::beforeUpdate()

You need to overload Phalcon\Mvc\Model::save() for this to work from within a model.

在结果集中操作(Operations over Resultsets)

If a resultset is composed of complete objects, the resultset is in the ability to perform operations on the records obtained in a simple manner:

更新关联表记录(Updating related records)

Instead of doing this:

  1. <?php
  2. $parts = $robots->getParts();
  3. foreach ($parts as $part) {
  4. $part->stock = 100;
  5. $part->updated_at = time();
  6. if ($part->update() === false) {
  7. $messages = $part->getMessages();
  8. foreach ($messages as $message) {
  9. echo $message;
  10. }
  11. break;
  12. }
  13. }

you can do this:

  1. <?php
  2. $robots->getParts()->update(
  3. [
  4. "stock" => 100,
  5. "updated_at" => time(),
  6. ]
  7. );

‘update’ also accepts an anonymous function to filter what records must be updated:

  1. <?php
  2. $data = [
  3. "stock" => 100,
  4. "updated_at" => time(),
  5. ];
  6. // Update all the parts except those whose type is basic
  7. $robots->getParts()->update(
  8. $data,
  9. function ($part) {
  10. if ($part->type === Part::TYPE_BASIC) {
  11. return false;
  12. }
  13. return true;
  14. }
  15. );

删除关联表记录(Deleting related records)

Instead of doing this:

  1. <?php
  2. $parts = $robots->getParts();
  3. foreach ($parts as $part) {
  4. if ($part->delete() === false) {
  5. $messages = $part->getMessages();
  6. foreach ($messages as $message) {
  7. echo $message;
  8. }
  9. break;
  10. }
  11. }

you can do this:

  1. <?php
  2. $robots->getParts()->delete();

delete() also accepts an anonymous function to filter what records must be deleted:

  1. <?php
  2. // Delete only whose stock is greater or equal than zero
  3. $robots->getParts()->delete(
  4. function ($part) {
  5. if ($part->stock < 0) {
  6. return false;
  7. }
  8. return true;
  9. }
  10. );