CairoCoder
CairoCoder

Reputation: 3189

Laravel | Using Eloquent hasManyThrough

I have a table called invoiceDetails that has item_id as foreign key from another table called items which has category_id as foreign key from table called categories.

I want to do that following using eloquent:

$result = InvoiceDetail::groupBy('item_id')
                ->selectRaw('sum(qty) as qty, item_id')->with('item', 'category')->get();

but I am getting error:

Call to undefined relationship [category] on model [App\InvoiceDetail].

Here's my relation inside Category model:

public function invoiceDetail() {
       return $this->hasManyThrough('App\InvoiceDetail', 'App\Item', 'category_id', 'item_id');
}

Any suggestions?

Upvotes: 0

Views: 1170

Answers (1)

Robert
Robert

Reputation: 5963

Not sure you would even need a hasManyThrough relation here, unless you want to fetch all InvoiceDatail objects belonging to all items which in turn belong to the Category. That part is not clear from your question.

But in your example you are fetching items with their category from distinct item_id.

The reason this is not working is because you are trying to fetch the category relation from the InvoiceDetail object, which does not exist.

->with('item', 'category')

You want to load the Category based on the item relation, not based on the InvoiceDetail, try the dot notation (given that you did define the other relations)

->with('item.category')

Relations should be like this:

class InvoiceDetail extends Model
{
    public function item()
    {
        return $this->belongsTo(\App\Item::class);
    }
}

class Item extends Model
{
    public function invoiceDetails()
    {
        return $this->hasMany(\App\InvoiceDetail::class);
    }

    public function category()
    {
        return $this->belongsTo(\App\Category::class);
    }
}

class Category extends Model
{
    public function items()
    {
        return $this->hasMany(\App\Item::class);
    }


    public function invoiceDetails()
    {
        return $this->hasManyThrough(\App\InvoiceDetail::class, \App\Item::class, 'category_id', 'item_id');
    }
}

You would want to use the hasManyThrough if, for example, you have a Category and you want to load all the InvoiceDetails directly.

dd($category->invoiceDetails);

Upvotes: 1

Related Questions