Laravel 5: Eloquent – relationship types: one to many

Eloquent: relationship types – one to many

DB tables used in examples: here.

one2many

One-to-many:
One post has many comments, but given comment belongs to single post.
ONE post has MANY comments: hasMany()
base notation

explanation:

  • method location – this method goes into parent Model – Post in this case
  • argument #1 – Comment: this is child object name
    it can be given as:

    • object name with path: App\Models\Comment
    • object name: Comment– required use App\Models\Comment
    • class name: Comment::class  – required use App\Models\Comment
  • argument #2foreign_key relation
    what is foreign key: column in table ‘comments‘ used to relate to table ‘posts‘, in other words: holding ‘posts‘ table main id
    this is optional, if foreign key name is a snake case of parent model name and suffix ‘_id’, in this case: post_id
    if your foreign_key name is different, you have to state it as argument #2
  • argument #3 – local_key relation
    what is local_key: it is primary key in posts (parent model) table
    Laravel expects it to be named id, if it is not, local_key must be given in hasMany method
how it looks like – example:

Inverse: ONE comment belongs to ONE post: belongsTo()
base notation

explanation:

  • method location – this method goes into child Model – Comment in this case
  • argument #1 – User: this is parent object name
    it can be given as:

    • object name with path: App\Models\Post
    • object name: Post– required use App\Models\Post
    • class name: Post::class  – required use App\Models\Post
  • argument #2foreign_key relation
    this is an argument on model, where this metod resides in – in this case: Comment model
    what is foreign key: column in table ‘comments’ used to relate to table ‘posts’, in other words: holding posts table main id
    this is optional, if foreign key name is a snake case of parent model name and suffix ‘_id’, in this case: post_id
    if your foreign_key name is different, you have to state it as argument #2
  • argument #3 – other_key relation (equivalent to local_key in hasMany)
    this is an argument on model, which is given in belongsTo statement – in this case: Post model
    what is other_key: it is primary key in users (parent model) table
    Laravel expects it to be named id, if it is not, other_key must be given in belongsTo method
how it looks like – example:

how to use it
Access data via Post object.
We can use Eloquent dynamic property.

Access data via Comment object.
We can use Eloquent dynamic property.