Laravel Eloquent Relationships | Laravel Has Many Through Eloquent Relationship Tutorial
Has Many Through relationship is a bit complicated to understand a provide shortcut way to access data of another mode relation. For example, a country is connected with users and users with posts, then we can access all posts connected with a specific country. has many through relationship in laravel.
So in this tutorial you can understand how to create has many through relationships with migration with a foreign key schema for one to many relationships, create records, attach records, get all records, where condition and everything related to has many through relationship.
In this example, I will create “users”, “posts” and “countries” tables. each table is connected with each other. now we will create many to many relationship with each other by using the laravel Eloquent Model. We will first create database migration, then models, retrieve records and then how to create records too. So you can also see database table structure on below screen.
Has Many Through Relationship will use “hasManyThrough()” for relation.
Create Migrations
Now we have to create migration of “users”, “posts” and “countries” table. we will also add foreign key with users and posts table. so let’s create like as below
users table migration
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('country_id')->unsigned();
$table->rememberToken();
$table->timestamps();
$table->foreign('country_id')->references('id')->on('countries')
->onDelete('cascade');
});
posts table migration
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string("name");
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade');
});
countries table migration
Schema::create('countries', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Create Models
Here, we will create Country model. we will also use “hasManyThrough()” for relationship of both model.
Country Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
Post::class,
User::class,
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
Retrieve Records
$country = Country::find(1);
dd($country->posts);
Post a Comment