Join no Eloquent - Join no Eloquent?

Asked

Viewed 1,277 times

2

I’m learning Laravel now, and out of curiosity I came across the following problem, performing a Join between two tables, in my case, "categorias" and "subcategorias", when I will list the subcategorias.

He would find the name of the category to which she is related and display it, I know it would be easier using the DB::, but for the sake of curiosity and learning I would like to know how to do this in the Eloquent?

Table Categories

id_categoria - PK
nome_categoria

Table Subcategories

id_subcategoria - PK
nome_subcategoria
idcategoria_subcategoria - armazena o id da categoria
  • Carlos?

  • Also read on: https://answall.com/help/accepted-answer and also https://answall.com/help to create and accept answers!

  • Virgilio, not yet, he doesn’t show the data, now I have a question, what do I put in the $p?? Because there will be several categories, if I specify one, it would not display only that?

  • managed to eibir, but it only displays of the specified category.

  • What did you want, because then your question is poorly formulated? Anything put in your question the gift idea DB:: that you said it would be easier! how would it be? then I can translate to Eloquent!

1 answer

0


First you need to configure your models :

Categories

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Categorias extends Model
{

    protected $table = 'categorias';
    protected $primaryKey = 'id_categoria';
    protected $fillable = ['nome_categoria'];
    public  $timestamps = false;

    public function subcategorias()
    {        
        return $this->hasMany(SubCategorias::class,
                              'idcategoria_subcategoria', 'id_categoria');
    }    
}

Subcategories

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class SubCategorias extends Model
{

    protected $table = 'subcategorias';
    protected $primaryKey = 'id_subcategoria';
    protected $fillable = ['nome_subcategoria', 'idcategoria_subcategoria'];
    public  $timestamps = false;

    public function categoria()
    {        
        return $this->belongsTo(Categorias::class,
                               'idcategoria_subcategoria', 'id_categoria');
    }    
}

Check that the table names are the same (categories and subcategories) that were placed in the settings protected $table if do not change to the name matches.

To do the research use whereHas as follows:

$p = 'texto de busca';
$subCategorias = SubCategorias::whereHas('categoria', function ($query) use ($p) {
    $query->where('nome_categoria', 'like', $p);
})->get();

References:

  • managed eibir, but it only displays the category specified in $p

Browser other questions tagged

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