Take column name with foreign key

Asked

Viewed 774 times

2

I have a product table that refers to id table categories, but do not want to take the number id of the foreign table, and yes the name of this reference.

My controller is like this:

public function index()
{
    $prod = Produto::all();
    return view('produtos', compact('prod'));
}

Dai in my view I call the name of categoria_id but I only get the ID number.

@foreach ($prod as $p)
<tr>
    <td>{{$p->id}}</td>
    <td>{{$p->nome}}</td>
    <td>{{$p->estoque}}</td>
    <td>{{$p->preco}}</td>
    <td>{{$p->categoria_id}}</td>
</tr>
@endforeach

How do I return the name of the category that references id of the products table?

  • Could [Dit] the question putting the class Produto, mainly showing how implemented the relationship between the models?

1 answer

3


What is missing really in your question are the relations of your two tables, and also the Models which are configured for these tables, where a Produto has Categoria and a Categoria is in several Produto, that is to say, a 1:N relationship. A fictional example about a product table and a category table where the two relate, example:

inserir a descrição da imagem aqui

Classes:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Produto extends Model
{
    protected $table = 'produtos';
    protected $fillable = ['categoria_id','descricao'];

    public function categoria()
    {
        return $this->belongsTo(App\Categoria::class,'categoria_id','id');
    }
}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Categoria extends Model
{
    protected $table = 'categorias';
    protected $fillable = ['nome'];

    public function produtos()
    {
        return $this->hasMany(App\Produto::class,'categoria_id','id');
    }
}

How to use:

public function index()
{
    $prod = Produto::with('categoria')->get();
    return view('produtos', compact('prod'));
}

@foreach ($prod as $p)
<tr>
    <td>{{$p->id}}</td>
    <td>{{$p->descricao}}</td>
    <td>{{$p->categoria->nome}}</td>
</tr>
@endforeach

In this example there are several important points:

  • Create entities' relationship by explicitly specifying the keys (if following the names you do not need to put, but, it is a good conduct to put mainly for maintenance)

  • Load forward interface (command with('categoria')), because, there is the optimization of only 2 queries SQL different from the other that each interaction and made a new query SQL causing slowness and a very common error in development with Laravel.

Ref.

Browser other questions tagged

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