Laravel Relationships: Defining Relationships
Defining Relationships
Defined as methods on your Eloquent model classes.
One To One
One To Many
Is used to define relationships where a single model owns any amount of other models.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
} One To Many (Inverse)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
} /**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key');
} Many To Many
Has Many Through
Provides a convenient shortcut for accessing distant relations via an intermediate relation.
Countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string Polymorphic Relations
Many To Many Polymorphic Relations
Retrieving The Relationship
Related concepts
→
Defining Relationships
→
- Defining Relationships: One To One
- Defining Relationships: One To Many
- Defining Relationships: One To Many (Inverse)
- Defining Relationships: Many To Many
- Defining Relationships: Has Many Through
- Defining Relationships: Polymorphic Relations
- Defining Relationships: Many To Many Polymorphic Relations
- Defining Relationships: Retrieving The Relationship
Semantic portal