Return Json with related data - Laravel

Asked

Viewed 2,115 times

2

I am creating a REST API but I stumbled upon this issue in which I cannot imagine a solution.

In my database I have 2 tables;

Table 1 - General product data such as name, code, sku and description

Table 2 - Variable product codes.

Table 3 - Images of the products

For example; Product X contains the sizes 1,2,3 and 2 images (these sizes and images are in separate tables from table 1).

How would I return a json with the related data between the tables? Currently I only managed to return one "all" from table 1, what would be the logic applied in this situation for me to return a json with product 1 and the variations of the same?

  • If I understand correctly, the three tables have in common the idProduto correct? Could you give an example of the data of each table for the idProduto : 1?

  • Tried some joins? or map models?

  • 1

    Table-1 = 1:1, Table-2 = 1:N, Tabela3 = 1:N?

  • I made a JOIN in my query and then I handled everything normally with PHP’s JSON functions. I would do what @rray said: try JOIN. I needed to create a JSON to generate a table with the jQuery jTable plugin, so I made a JOIN, which returns a view with the junction of several tables as if they were one, which is indifferent to PHP that generate the JSON.

1 answer

1


I was able to find the solution in this topic.

After creating the relationship in both the controller, models and Migrations;

Basically what should be done to fetch the related data is:

$dados = Post::with('Comments')->get();
return response()->json($dados);

Taking into consideration oneToMany relationship

  • Mark as resolved ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.