Laravel make a relationships with different column names in the same table
In Laravel, establishing relationships between models when the foreign key and local key have different names is a common requirement. This scenario is often referred to as "self-referential relationships with different column names." Here's how you can create such relationships in Laravel using Eloquent ORM.
First, let's define the terms:
- Local key: The primary key of the current model.
- Foreign key: The key in the related model that refers to the current model.
Assuming we have a Post
model with a self-referential relationship and different column names for the local and foreign keys, we can define the relationship in the Post
model as follows:
protected $primaryKey = 'id'; // Default local key
protected $table = 'posts'; // Table name
protected $fillable = ['title', 'content', 'parent_id']; // Fillable columns
public function child()
{
return $this->hasOne('App\Post', 'id', 'parent_id');
}
public function parent()
{
return $this->belongsTo('App\Post', 'parent_id', 'id');
}
In the example above, we have a Post
model with a self-referential relationship. The id
column is the local key, and parent_id
is the foreign key. We define the relationship using the hasOne
method for the child relationship and the belongsTo
method for the parent relationship.
The first argument of both methods is the related model (App\Post
), the second argument is the local key (id
), and the third argument is the foreign key (parent_id
).
Now, you can use these relationships in your controllers or views as follows:
// In a controller
$post = App\Post::find(1);
$parentPost = $post->parent;
// In a view
@extends('layouts.app')
@section('content')
<p>Post title: {{ $post->title }}</p>
<p>Parent post title: {{ $post->parent->title }}</p>
@endsection
This way, you can create relationships with different column names in the same table using Laravel Eloquent ORM.