Query in related tables

1

As would be an example of querying a bd with related tables and inserting data into them.

I have the tables:

Produtos  
Tamanhos   
Generos

I need to display in the view produtos.blade.php a list with all the registered products and also their tamanho and genero fields that are identified by their id's in the produtos table.

EDIT:

I've posted my models view and route code here: link

There are the errors that are returning there

//model Produto
<?php
class Produto extends Eloquent
{
        // Produtos has_many Tamanhos
        public function tamanhos()
        {
                return $this->hasMany('Tamanho');
        }
}

//model tamanho
<?php
class Tamanho extends Eloquent
{
        public $timestamps = false;

        // Tamanhoss belongs_to Produtos
        public function produtos()
        {
                return $this->belongsTo('Produto');
        }
}


//route com o eloquent
Route::get('/teste', function()
{
        $produtos = Produto::all();
        return View::make('produto.teste', compact("produtos"));
});


//foreach da view
 @foreach($produtos as $produto)
                <tr>
                    <td><input type="text" value="{{ $produto->tamanho->descricao }}" name="title" /></td>
                </tr>
 @endforeach


//Erro exibido na tela
Trying to get property of non-object

/* se eu mudo no foreach da view $produto->tamanho->descricao por $produto->tamanhos->descricao
me dá esse erro:
*/
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tamanhos.produto_id' in 'where clause' (SQL: select * from 'tamanhos' where 'tamanhos'.'produto_id' = ?) (Bindings: array ( 0 => 1, ))



sendo que na tabela produtos tem o campo tamanho_id para servir como chave estrangeira com a tabela tamanhos
    
asked by anonymous 07.02.2014 / 18:07

2 answers

1

You see, Henry ... I have answered another question from you today ... but only now I have noticed several things ... you are not defining relations correctly. We have to "go back a little" and think better:

1st - You have a schematic in the database, right? As far as I can tell, in your "products" table you have a "size_id" field. In this case, this is defining a one-to-many relationship, where ONE SIZE can be assigned to MANY PRODUCTS (and simultaneously many-to-one < strong>, where VARIOUS PRODUCTS CAN HAVE A SINGLE SIZE).

2nd - In your model, you define a "sizes" property, and a hasMany relation. This is wrong . That would only be right if A PRODUCT MIGHT HAVE VARIOUS SIZES . The right way to put the relationship you want, on the templates, is as follows:

//model Produto
<?php
class Produto extends Eloquent
{
    // Produto belongs to Tamanho
    public function tamanho()
    {
        return $this->belongsTo('Tamanho');
    }
}

//model tamanho
<?php
class Tamanho extends Eloquent
{
    public $timestamps = false;

    // Tamanho has many Produtos
    public function produtos()
    {
        return $this->hasMany('Produto');
    }
}

Once the templates are fixed and consistent with the database schema, you can use the with method to prevent a new "SELECT" from executing with every LOOP interaction that will display the products in the < in> view . For example:

//route com o eloquent
Route::get('/teste', function()
{
    $produtos = Produto::with('tamanho', 'genero')->get();
    return View::make('produto.teste', compact("produtos"));
});

Finally, view will work the way it is:

@foreach($produtos as $produto)
    <tr>
        <td><input type="text" value="{{ $produto->tamanho->descricao }}" name="title" /></td>
    </tr>
@endforeach
    
07.02.2014 / 20:00
1

If you're using Eloquent , just set the relationships in the model produtos and Laravel does the magic for you.

In your product model, use the following code to connect:

public function tamanho()
{
     //Aqui deve ser posto o nome do model para a tabela tamanho.
     return $this->belongsTo('tamanho'); 
}

... the same should be done for generos .

Once this is done, just iterate over the list of products (with foreach , for example) and directly access information from related tables as if they were attributes of the produto object.

$produto->tamanho->valor

... for example, is a way to access the valor field, contained in the tamanho table via the produto object.

The Eloquent is simply one of the most beautiful things I've ever seen inside the PHP world. ; D

... hope it helps!

EDIT 1:

If your produtos has a foreign key for tamanhos , then the relation is not hasMany and yes belongsTo .

    
07.02.2014 / 18:22