0

There are 3 models:

First (first_id)
Connection (connection_id, first_id, product_id)
Second (second_id, product_id)

I would like to connect the three models together using laravel relationships

First->joined to Connection though first_id Connection->joined to First through first_id, & joined to Second through product_id Second -> joined to Connection through product_id

So: First joined to Second through Connection first_id, product_id

Is this possible to do using something like HasManyThrough?

Thanks for your time

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
user2101517
  • 700
  • 3
  • 11
  • 22

3 Answers3

1

On your First model:

public function second () {
    return $this->hasManyThrough(
        Second::class, 
        Connection::class, 
        'product_id', // Foreign key on connection table
        'product_id', // Foreign key on second table
        'first_id', // Local key on first table
        'first_id' // Local key on connection table
    );
}

Based on your description the column names should work.

In tinker you can validate if it's hooked up correctly by doing something like First::first()->second.

FunkyMonk91
  • 1,469
  • 1
  • 17
  • 30
1

It depends on what type of relationship Your first model and second model shares as well as what type of relation second and third model shares.

if consider your first model First and second model Second shares a one-to-one relation, as well as Second model and Third models shares one-to-one relationships.

It will be $first->second->third; //no has many through relationship requires

If your First model and Second models shares as hasMany-belongs to relation than you need to use hasManyThrough relationship

example from doc

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            '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...
        );
    }
}
Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
1

You can try using nested relationships.

Nested Eager Loading To eager load nested relationships, you may use "dot" syntax. For example, let's eager load all of the book's authors and all of the author's personal contacts in one Eloquent statement:

$books = App\Book::with('author.contacts')->get();

Book Model:

public function author() 
{
    return $this->hasOne('App\Author');
}

Author Model:

public function contacts() 
{
    return $this->hasMany('App\Author');
}

Documentation:

https://laravel.com/docs/5.8/eloquent-relationships

jkruskie
  • 412
  • 4
  • 15