Json with relationship Manytomany - Laravel

Asked

Viewed 462 times

4

I created a relationship between my tables using ManyToMany and currently I need to return a Json with the information, but my tables meet this way;

// 1. Produtos
+-------------+
| id          |
| name        |
| description |
| image       |
|_____________|
// 2. Variações
+-------------+
| id          |
| SKU         |
|_____________|
// 3. Produtos_variacoes
+-------------+
| prod_id     |
| variation_id|
|_____________|

1 - The table Produtos stores general product information.

2 - The table Variações stores the codes that the product has

3 - The table produtos_variações serves as a "pivot" for storing id of the product and the id of variation.

When I return a Json between 2 tables I do it this way;

$dados = Product::with('Variacoes')->get();
return Response::json($dados);

But I need to relate the table produtos_variações to be able to know which product has which variation.

How can I do that?

  • How JSON is being returned today?

  • if I use the example I showed in the post this returning a list of products with a list of variations, however these tables have no relationship between themselves.

  • This is returned in the field pivot of your json

  • Your question is not very clear. Why you need to relate produtos_variacoes? Isn’t it already related? You have set up your belongsToMany?

1 answer

1

First by Laravel convention, the name of your table Many to Many should be singular and in alphabetical order. Rename your table to produto_variacao

In your Product model (table name: products)

public function variacoes() {
    return $this->belongsToMany('App\Variacao');
}

In your model Variacao (table name: variacoes)

public function produtos() {
    return $this->belongsToMany('App\Produto');
}

In the first it means that a Product belongs to many variations.

The second means that a Variation belongs to many products.

On your controller:

public function index() {
    $a = App\Produto::find(1)->variacoes; // retorna todas as variações do produto com id 1.
    $b = App\Variacao::find(1)->produtos; // retorna todos os produtos da variação com id 1.
    $c = App\Produto::with('variacoes')->get(); // retorna os produtos as variações embutidas.

    return response()->json($a);
}

Test the 3, one of them will solve your problems. I recommend installing Chrome’s Postman extension to test the return of JSON’s. Don’t forget to set the route file correctly too.

Browser other questions tagged

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