Vijay Kumar
Vijay Kumar

Reputation: 51

Unable to make relation in has-one-through

I'm trying to make an relationship in has-one-through.

Tables:

packages
    -guest_detail_id

guest_details
    -client_id

clients
    -id

in Package.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Packages extends Model {
  /**
   * Get the client.
   */
  public function client() {
      return $this->hasOneThrough(---what will be params---);
  }
}

Upvotes: 0

Views: 71

Answers (2)

Sandeep Sudhakaran
Sandeep Sudhakaran

Reputation: 1092

In your question, I found that one package has one client. which cannot implement through a direct relation. this could be done through hasOneThrough() relation ship.

hasOneThrough() relation can be achieved through a intermediate table, here yourguest_details. so the relation becomes One package has one GuestDetails and one GuestDetails has one client, hence one package has one Client.

 public function client() {
    return $this->hasOneThrough(Client::class, GuestDetails::class, 'client_id', 'id');
 }

Upvotes: 1

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You are basically looking for a BelongsToThrough relationship, so you have to swap the foreign and local keys:

public function client() {
    return $this->hasOneThrough(
        Client::class, GuestDetails::class,
        'id', 'id',
        'guest_detail_id', 'client_id'
    );
}

Upvotes: 0

Related Questions