query between 2 tables

Asked

Viewed 2,825 times

0

I have the product tables(tbl_products) and the categories table(tbl_categories):

- tbl_produtos -
id_produto
nome
id_categoria

- tbl_categorias -
id_categoria
nome

What I want is to present in the view the list of products, in which for each product, says the name of the category that is related. What is the best option to do this query? No model or problem to do in controller?

In my controller I have the following:

public function getIndex(){
    $produtos= ProdutoDados::get(); 
    return View::make('produtos.lista', compact('produtos')); 
}

In the product model I have only the following:

<?php
    class ProdutosDados extends Eloquent{
        protected $table = 'tbl_produtos';
        protected $primaryKey = 'id_produto';
        protected $guarded = array('id_produto'); 
    }
?>

Model categories:

<?php
    class CategoriaDados extends Eloquent{
        protected $table = 'tbl_categorias';
        protected $primaryKey = 'id_categoria';
        protected $guarded = array('id_categoria'); 
    }
?>
  • How is the relationship between your models?

  • I changed the question @gmsantos

1 answer

2


There are many ways to do it...

But there are two I always use. Using JOIN in Laravel or using relationship functions in the corresponding Model.

Using JOIN:

$query = DB::table('tbl_produtos')
             ->join('tbl_categorias', 'tbl_produtos.id_categoria', '=', 'tbl_categoria.id')
             ->select('tbl_produtos.nome as Produto', 'tbl_categorias.nome as Categoria')
             ->get();

Using Relationship in Model - The link below can help you.

http://laravel.com/docs/4.2/eloquent#one-to-one

Browser other questions tagged

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