Peter Griffin
Peter Griffin

Reputation: 300

Laravel hasManyThrough() returning no results

I have 3 tables and I want to join 2 of them through another using eloquent

ProductGroup table

--------------------------
| ProductGroupId | Name  |
-------------------------
| 1              | Test1 |
| 2              | Test2 |
--------------------------

ProductLine table
-------------------------------------------------
| ProductLineId | ProductGroupId | Name         |
------------------------------------------------|
| 1              | 1             | AnotherTest1 |
| 2              | 1             | AnotherTest2 |
-------------------------------------------------

ProductType table
----------------------------------------------
| ProductTypeId | ProductLineId | Name       |
---------------------------------------------|
| 1             | 1             | Something1 |
| 2             | 1             | Something2 |
----------------------------------------------

I want to join ProductGroup with ProductType

I tried using this as my ProductGroup model (not sure if I've done the hasManyThrough() correctly)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductGroup extends Model
{
    protected $primaryKey = 'ProductGroupId';
    public $timestamps = false;

    public function producttype()
    {
        return $this->hasManyThrough('App\ProductGroup', 'App\ProductLine', 'ProductGroupId', 'ProductGroupId');
    }
}

I want to join the 2 tables on a particular id from the ProductGroup table so really in SQL it would be

SELECT * FROM ProductType pt
        INNER JOIN ProductLine pl ON 
            pt.ProductLineId = pl.ProductLineId
        INNER JOIN ProductGroup pg ON 
            pg.ProductGroupId = pl.ProductGroupId
    WHERE pg.ProductGroupId = 3

I have tried this but I get no results

I could do this in query builder but i'd rather use eloquent if it can be helped

$test = ProductGroup::with('producttype')->whereHas('producttype', function ($query) {
    $query->where('ProductGroup.ProductGroupId', 3);
})->get();

Upvotes: 0

Views: 171

Answers (1)

AdRock
AdRock

Reputation: 3096

Change

public function producttype()
{
    return $this->hasManyThrough('App\ProductGroup', 'App\ProductLine', 
    'ProductGroupId', 'ProductGroupId');
}

to

public function producttype()
{
    return $this->hasManyThrough('App\ProductType', 'App\ProductLine', 'ProductGroupId', 'ProductLineId');
}

Upvotes: 1

Related Questions