Skip to content
Advertisement

How do I get all of the results from a hasMany() relationship in Laravel?

For example, I have a Product, and I have a BaseProduct.

In the model for the Product, I’ve specified the following:

JavaScript

In the BaseProduct, I’ve specified the following relationship:

JavaScript

If I were to select a product, like so:

JavaScript

I could get the BaseProduct by doing the following:

JavaScript

Instead of getting the array of the result from that, how would I get the Model of the BaseProduct, so I can get all of the children of BaseProduct, meaning all Products that have a foreign key relating to this BaseProduct.

I’ve tried BaseProduct()->all(); instead, but it isn’t a valid method.


Edit:

I’ve created the following chain of function calls – but it’s awful.

JavaScript

Final edit:

I had made a mistake in my BaseProduct model. In the Products() function, I had specified return $this->hasMany("Product", "ProductId"); where ProductId should have been BaseProductId.

After I fixed that, I could successfully use:

JavaScript

As Sheikh Heera had explained.

Advertisement

Answer

To get the children of the BaseProduct you may try this:

JavaScript

Now, you have a collection of BaseProduct so, you may use something like this:

JavaScript

Or get the second item from collection

JavaScript

Also, you may run a loop like this (most probably in the view after pass it):

JavaScript

In the View

JavaScript

Update: Yes, you may try this

JavaScript

You may chain like:

JavaScript

Update: Your table structure should look something like:

Table:baseproduct:

JavaScript

Table:products:

JavaScript

According to this table structure, relationship should be

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement