Get inverse relationship with Laravel

Asked

Viewed 394 times

7

I am creating a forum system that is divided by sections. Each section contains categories, each category contains topics. Ex:

Administração _
               |_Regras da do fórum
               |_Sugestões e críticas

Aeromodelismo _
               |_Elétricos _
               |_Glow       |-Tópico 1
                            |-Tópico 2
                            |-Tópico N

When entering the forum I need to pick up the last topics answered where (Where) id of section = X.

In summary I need to get the last topics answered within a specific section, but one has to consider that in the table 'topics' the foreign key references the category, and in the table 'categories' the foreign key references the section, that is, the topics are 'grandchildren' of the sections.

2 answers

4


Well, I would implement it that way:

It would unify categories and sessions into a single table by adding an "id_parent" column, referencing the table itself and allowing nulls. So the sessions would be the categories with id_pai null.

To return the topics of a specific session, just one DB::table('sessoes')->where('id_pai', 4)->get()->toArray(); to have an array with the id of all categories and finally use this array in a query with whereIn

Example:

$categorias = DB::table('sessoes')->where('id_pai', 4)->get()->toArray();
$topicos = DB::table('topicos ')
                    ->whereIn('id',$categorias)->get();

1

  • The problem isn’t order. I need to take the topics that are 'grandchildren' of a session, but without having to do that lot of query to get the categories that are daughters of the session and then pick up the topics that are children of the categories.

  • I thought it wasn’t, but then take and edit your question with the code you’re using.

  • That’s the problem, I can’t even think about how I’m going to do it. I don’t have code yet.

Browser other questions tagged

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