How To Define Has One Through Relationships With Laravel

admin_img Posted By Bajarangi soft , Posted On 07-09-2020

The "has-one-through" relationship links models through a single intermediate relation.

How To Define Has One Through Relationships With Laravel

Has One Through Relationships

Lets start.
How to define Has One Through Eloquent Relationship

For example, in a Bike repair shop application, each BikeMechanic may have one Bike, and each Bike may have one Owner. While the Mechanic and the Owner have no direct connection, the BikeMechanic  can access the Owner through the Bike itself. Let's look at the necessary details:


1.Create laravel project and connect to database in .env file.

composer create-project laravel/laravel BikeRepairShop --prefer-dist


2.Create Model and Migrate it.
To implement  Has One Through Relationships in Laravel, we need models: BikeMechanic ,Bike and Owner.

Now we need to create BikeMechanic ,Bike  and  Ownermodels in fresh project so for that run below commands in comand prompt.

php artisan make:model BikeMechanics -m

php artisan make:model Bike -m

php artisan make:model Owner -m


3.After Created Models we need to Implement code in Model and migration files as below
Migration files

2020_09_07_100624_create_bike_mechanics_table.php

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBikeMechanicsTable extends Migration
{
    public function up()
    {
        Schema::create('bike_mechanics', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('bike_mechanics_name');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('bike_mechanics');
    }
}


2020_09_07_100705_create_bikes_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBikesTable extends Migration
{
public function up()
    {
        Schema::create('bikes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('model');
            $table->bigInteger('mechanic_id ')->unsigned()->index();
            $table->foreign('mechanic_id ')->references('id')->on('bike_mechanics')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }
 public function down()
    {
        Schema::dropIfExists('bikes');
    }
}

2020_09_07_100750_create_owners_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOwnersTable extends Migration
{
  public function up()
    {
        Schema::create('owners', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->bigInteger('bike_id')->unsigned()->index();
            $table->foreign('bike_id')->references('id')->on('bikes')
                ->onDelete('cascade');
            $table->timestamps();
        });
    }
public function down()
    {
        Schema::dropIfExists('owners');
    }
}


migrate the schema files using the following command

php artisan migrate


Models
BikeMechanics.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BikeMechanics extends Model
{
    protected $fillable = [
       'bike_mechanics_name'
    ];

public function BikeOwner()
    {
        return $this->hasOneThrough(
            'App\Owner',
            'App\Bike',
            'mechanic_id', // Foreign key on products table...
            'bike_id', // Foreign key on orders table...
            'id', // Local key on suppliers table...
            'id' // Local key on products table...
        );
    }
}

Bike.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Bike extends Model
{
protected $fillable = [
      'model', 'mechanic_id',
   ]; 
}


Owner.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Owner extends Model
{ 
 protected $fillable = [
    'name', 'bike_id', 
    ];
}
 

4.Create route and controller to access data.
Route in Web.php

Route::get('hasone','BikeshopController@hasone');

Create BikeshopController.php  using below command in command prompt

php artisan make:controller BikeshopController

BikeshopController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\BikeMechanics;
use App\Bike;
use App\Owner;

class OneController extends Controller
{
    //
    public function hasone()
    {
        $BikeMechanics = BikeMechanics::find(1);
        $BikeMechanics_one = $BikeMechanics->name;
        print_r($BikeMechanics_one);

        $BikeMechanics = BikeMechanics::find(2);
        $BikeMechanics_two = $BikeMechanics->name;
        print_r($BikeMechanics_two);

        return 'done';

    }
}

Related Post