First you need to configure your models eloquent:
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:
Carlos?
– novic
Also read on: https://answall.com/help/accepted-answer and also https://answall.com/help to create and accept answers!
– novic
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?
– Carlos Eduardo Silva
managed to eibir, but it only displays of the specified category.
– Carlos Eduardo Silva
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!– novic