Consult multiple tables in Laravel 5.1


I have this query in which you are looking for products and the category to which they belong:

$products = Product::product($product)

return view('mega/product/list', compact('products'));

What I want is to consult the price table in that same query. How could I do it?

asked by DonPoshe 04.01.2016 в 16:16

2 answers


If in the model you indicate the relationship you have solved the problem:


namespace App;
use Illuminate\Database\Eloquent\Model;

class Producto extends Model
    protected $table = 'tbProductos';
    protected $id='id';

    public $timestamps = false;     //true valor por defecto
    public $incrementing = true;    //true valor por defecto

    public function precio()
         return $this->hasOne('App\Precio');

With this you can use eloquent to access directly

$precio = Product::product($id)->precio()

You have to be VERY clear about the data model. Who is the owner of the relationship and who is has the fk. It is advisable to understand how the model is translated into tables. You can also explicitly indicate the foreign keys but it is not necessary:

public function precio()
     return $this->hasOne('App\Precio', fk_precio);

Important: Normally lazy loading is used. That is, they only ask for the data when they are needed, which can generate performance problems. If you want to bring the data in one step, you have to indicate it explicitly using the eager loading using the with


see: link

answered by 26.02.2016 в 14:44

Price is related to product?

Because if it is so you could use the relationship with another foreach, it would be something like:

@foreach($products as $product)
       @foreach($product->precios as $precios)
           <p>Precios de este producto</p>
            {!! $precios->precio !!}
answered by 21.01.2016 в 07:10