Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
How to set a One To Many relationship in ONE model between different types

I have a table named categories and here is it's structure:

id              bigint(20)      AUTO_INCREMENT  
name            varchar(255)    
description     varchar(255)    
short_name      varchar(255)    
picture         varchar(255)    
parent_category int(11)
category_type   tinyint(4)  

So each category has a category_type which can be one of these values:

1: Main Category

2: Superior Category

3: Secondary Category

4: Secondary Sub Category

Now I wanted to set a One To Many relationship between these categories.

For example: a main category has many superior categories and a superior category is related to one main category.

And this will apply to the rest of them as well.

But because I have only one Model which is Category, I don't know how to apply this relationship, so if you know, plz help me out...

Model Category.php:

class Category extends Model
{
    use HasFactory;
    protected $fillable = ['name','short_name','description','picture','category_type','parent_category'];

}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can write the following relations in the Category model:

public function parentCategory()
{
    return $this->belongsTo(Category::class, 'parent_category', 'id');
}

public function childCategories()
{
    return $this->hasMany(Category::class, 'parent_category', 'id');
}

You can later fetch the relations for example like this:

$cat = Category::where('category_type', 'main')->first();
$cat->childCategories; //all the categories where the main category has been set as parent category

Or

  $cat2 = Category::where('category_type', 'secondary')->first();
  $cat2->parentCategory; //the category object which has been marked as parent for that specific secondary category

If you want to filter per category type on the relations, you can do this as well:

public function superiorChildCategories()
{
    return $this->hasMany(Category::class,'parent_category','id')->where('category_type','superior');
}

To use:

$cat3 = Category::where('category_type', 'main')->first();
$cat3->superiorChildCategories; //all the superior type categories where the main category has been set as parent category, will return null if there is no superior type child categories

Don't forget to set the actual parent type relation on the database as well, so parent_category column should be the id of the parent category.

It is also tested, and works as expected.

over 4 years ago · Santiago Trujillo Relatório

0

As I know, Laravel relationships work between models and not within one model. I would recommend you to use separate models (and separate tables).

If all other categories are on the same level and they all belong to one main category, you can make one model for the main category and all others can have one model.

over 4 years ago · Santiago Trujillo Relatório

0

public function parent_category()
{
    return $this->hasMany(Category::class,'parent_category','id');
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda