Consult multiple tables in Laravel 5.1

3

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

$products = Product::product($product)
                          ->category($category)
                          ->with('category')
                          ->orderBy('id','DESC')
                          ->paginate(7);

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
source

2 answers

2

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

<?php

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

operator

see: link

    
answered by 26.02.2016 в 14:44
1

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 !!}
       @endforeach
@endforeach
    
answered by 21.01.2016 в 07:10