Eloquent models

  • In the previous section, we created model classes for all the database tables
    • All models can be found in the root of the app folder
    • The Eloquent ORM (Object-Relational Mapping) included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database
      • Each database table has a corresponding model which is used to interact with that table
      • In fact, the model represents a single row in the table
      • Models allow you to query for data in your tables, as well as insert, update or delete a specific table row

Add relationships

  • The relations between the primary keys and foreign keys are already defined in MySql (through the code in the corresponding migrations)
  • It's also necessary to define those relations in the Eloquent models
  • The database of our application only contains one-to-many and many-to-one relations

Genre 1 <-> ∞ Record

  • If we consider this relation as a one-to-many (1 -> ∞) relationship, we can say that "a genre has many records"
    • In Eloquent, we define this relationship by applying the hasMany() method on our Genre model, with the Record model ('App\Record') as parameter
    • Eloquent will automatically determine the proper foreign key column in the Record model, i.e. genre_id (the name of the owning model, suffixed with _id)
    • The former code should be wrapped in a method records(), which shall be used later on to query all the records of a specific genre


 
 
 
 


class Genre extends Model
{
    public function records() 
    {
        return $this->hasMany('App\Record');   // a genre has many records
    }
}
1
2
3
4
5
6
7

NAMING CONVENTIONS hasMany()

The relationship method should be named according to the used model (with lower case), and plural case
Full method: hasMany('model', 'foreign_key', 'primary_key')

  • The first parameter is the model to refer to (Record)
  • You may omit the third parameter if the primary key of the referred model (Record) is named id
  • You may omit the second parameter if the foreign key of the owning model (Genre) is the the "snake_case" name of the owning model, suffixed with _id
class Genre extends Model
{
    public function records()
    {
        // long version
        return $this->hasMany('App\Record', 'genre_id', 'id'); 
        // short version
        return $this->hasMany('App\Record'); 
    }
}
1
2
3
4
5
6
7
8
9
10

More info: One To Many

  • Inversely, we can look at the same relation as a many-to-one (∞ -> 1) relationship: "a record belongs to a genre"
    • In Eloquent, we define this relationship by applying the belongsTo() method on our Record model, with the Genre model ('App\Genre') as parameter
    • Eloquent will try to match the genre_id from the Record model to an id in the Genre model
      • The withDefault() method returns an empty Genre model (instead of null) if the genre_id does not match an id in the Genre model, which results in less conditional checks (and is often referred to as the Null object pattern)
    • The former code should be wrapped in a method genre(), which shall be used later on to query the genre of a specific record


 
 
 
 


class Record extends Model
{
    public function genre() 
    {
        return $this->belongsTo('App\Genre')->withDefault();   // a record belongs to a genre
    }
}
1
2
3
4
5
6
7

NAMING CONVENTIONS belongsTo()

The relationship method should be named according to the used model (with lower case), and singular case
Full method: belongsTo('model', 'foreign_key', 'primary_key')

  • The first parameter is the model to refer to (Genre)
  • You may omit the third parameter if the primary key of the referred model (Genre) is named id
  • You may omit the second parameter if the foreign key of the owning model (Record) is named the name of the relationship method, suffixed with _id
class Record extends Model
{
    public function genre() 
    {
        // long version
        return $this->belongsTo('App\Genre', 'genre_id', 'id')->withDefault();
        // short version
        return $this->belongsTo('App\Genre')->withDefault();
    }
}
1
2
3
4
5
6
7
8
9
10

More info: One To Many (Inverse)

EXERCISE: Define the other relations in the Eloquent models

User 1 <-> ∞ Order


 
 
 
 

// App/User.php
public function orders() 
{
    return $this->hasMany('App\Order');   // a user has many orders
}
1
2
3
4
5

 
 
 
 

// App/Order.php
public function user() 
{
    return $this->belongsTo('App\User')->withDefault();   // an order belongs to a user
}
1
2
3
4
5

Order 1 <-> ∞ Orderline


 
 
 
 

// App/Order.php
public function orderlines() 
{
    return $this->hasMany('App\Orderline');   // an order has many orderlines
}
1
2
3
4
5

 
 
 
 

// App/Orderline.php
public function order() 
{
    return $this->belongsTo('App\Order')->withDefault();   // an orderline belongs to an order
}
1
2
3
4
5

SUMMARY

Summary models

Last Updated: 10/19/2021, 3:56:36 PM