Join in Eloquent - Join in Eloquent?

2

I'm learning Laravel now, and out of curiosity I came across the following problem, doing a join between two tables, in my case, " categorias " and " subcategorias ", when I'm going to list the subcategorias .

It looks for the name of the category to which it is related and displays it, I know it would be easier using DB:: , but for curiosity and learning would like to know how to do it in Eloquent ?

Table Categories

id_categoria - PK
nome_categoria

Table Subcategories

id_subcategoria - PK
nome_subcategoria
idcategoria_subcategoria - armazena o id da categoria
    
asked by anonymous 12.05.2017 / 06:57

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');
    }    
}

Make sure that table names are the same (categories and subcategories) that have been placed in the protected $table settings if you do not change to the corresponding name.

To search, use whereas as follows:

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

13.05.2017 / 00:16