Model Relationships

The data that applications manipulate is usually structured in some way. Objects have links to other objects, and the model layer that represents that data should reflect the structure inherent in the data it represents and interacts with.

li3’s data layer offers a way to facilitate data relationships and structure. This guide is meant to show you how to specify and define these data relationships and use them to your advantage as you build your application.

Defining Model Relationships

Before you define a model relationship in your code, it’s important to understand the terminology that describes a relationship between two objects in your system. In li3 (and elsewhere), a specific set of terms are used to describe model relationships:

  • hasOne: the current object is linked to a single object of another type
  • hasMany: the current object is linked to many objects of another type
  • belongsTo: the current object is owned and marked as related to another object

If you’re having a hard time remembering hasOne/hasMany versus belongsTo, just
remember this: if the current model contains some sort of marker (like a foreign key), it
belongsTo another model.

Defining this object relationship is simple: you populate special properties on the model object. For example, let’s say we’re building an online store. Each Category is filled with many Product objects. In this case, we’d want to specify Category hasMany Product. Let’s see how this is done:

  1. class Categories extends \lithium\data\Model {
  2. public $hasMany = ['Products'];
  3. }

This simple declaration relies on convention, and is the functional equivalent to this:

  1. class Categories extends \lithium\data\Model {
  2. public $hasMany = ['Products' => [
  3. 'to' => 'Products',
  4. 'key' => 'category_id',
  5. 'constraints' => [],
  6. 'fields' => [],
  7. 'order' => null,
  8. 'limit' => null
  9. ]];
  10. }

Unless specified otherwise, the relationship assumes you’re using the exact class name specified, with a key that is an under_scored version of the model’s class name, suffixed with _id. All other sorting and limit options are assumed to be empty.

All of the model relationships use these same keys (although there’s no reason to order or limit hasOne or belongsTo) and can be configured likewise.

Once a relationship as been configured, you can use your models to fetch related data. We can now do this in a controller:

  1. $categories = Categories::find('all', [
  2. 'with' => 'Products'
  3. ]);
  4. print_r($categories->to('array'));
  5. /* outputs:
  6. Array
  7. (
  8. [id] => 1
  9. [name] => Audio
  10. [products] => Array
  11. (
  12. [0] => Array
  13. (
  14. [id] => 1
  15. [category_id] => 1
  16. [name] => Headphones
  17. [price] => 21.99
  18. )
  19. [1] => Array
  20. (
  21. [id] => 2
  22. [category_id] => 1
  23. [name] => Desk Speakers
  24. [price] => 39.95
  25. )
  26. [2] => Array
  27. (
  28. [id] => 3
  29. [category_id] => 1
  30. [name] => Portable Radio
  31. [price] => 9.95
  32. )
  33. )
  34. )
  35. */

Notice the new with key supplied to the model? This tells the model that you want related data joined to the normal result.

As you can see from the output, the related data has been added on to the model result. While we’re printing out array contents here, you can as easily loop through or access the same information at $categories->products in this case as well.

Ordering data works mostly as you’d expect it to. The following returns
all categories and their associated products first unsorted and than sorted
by the category title.

Good practice is to qualify fields (with the model name) in such queries to make the
statement unambigous.

  1. Categories::find('all', [
  2. 'with' => 'Products'
  3. ]);
  4. Categories::find('all', [
  5. 'with' => 'Products',
  6. 'order' => ['Categories.title']
  7. ]);

To have the nested products themselves sorted inside the ->products, you
add the qualified relationship field to the order statement.

  1. Categories::find('all', [
  2. 'order' => ['Categories.id', 'Products.price'],
  3. 'with' => 'Products'
  4. ]);

Did you note that we also added Categories.id in there? This is to keep
a consistent result set.


Sorting the whole result set just by the products
price alone is not possible.

If you see an exception thrown (Associated records hydrated out of order.), than
simply order by the main models primary key first. Other frameworks will magically
rewrite the query for you and add that primary key automatically. li3 however has
decided against this, as it doesn’t want to mess with your queries.

Because relationship setup is simple, so is saving related data. When saving related data, just make sure the proper key values are set so that the underlying data storage engine can match up the data correctly.
Here’s a simplified example of how we’d save a newly created product, matched up to a category. First, the ProductsController:

  1. namespace app\controllers;
  2. use \app\models\Products;
  3. use \app\models\Categories;
  4. class ProductsController extends \lithium\action\Controller {
  5. public function create() {
  6. // If form data has been submitted, create a new Product.
  7. if ($this->request->data) {
  8. Products::create($this->request->data)->save();
  9. }
  10. // Create a list of categories to send to the view.
  11. $categories = Categories::find('all');
  12. $categoryList = [];
  13. foreach ($categories as $category) {
  14. $categoryList[$category->id] = $category->name;
  15. }
  16. $this->set(compact('categoryList'));
  17. }
  18. }

And, here is the view that contains the form:

  1. <?= $this->form->create() ?>
  2. <?= $this->form->select('category_id', $categoryList) ?>
  3. <?= $this->form->text('name') ?>
  4. <?= $this->form->text('price') ?>
  5. <?= $this->form->submit('Create Product') ?>
  6. <?= $this->form->end() ?>