Json with relationship ManyToMany - Laravel

4

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

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

1 - The Produtos table stores general product information.

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

3 - The produtos_variações table serves as the "pivot" to store the id of the product and id of the variation.

When I return a Json between 2 tables I do the following way;

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

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

How can I do this?

    
asked by anonymous 02.12.2015 / 17:48

1 answer

1

Firstly by Laravel convention, the name of your many to many table should be in the 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 Variation (table name: variances)

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

At first it means that a Product belongs to many variations.

In the second it means that a Variation belongs to many products.

In 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 the Chrome Postman extension to test the return of the JSON's. Do not forget to set up the route file correctly too.

    
30.04.2016 / 10:52