P
P
photosho2017-04-05 11:15:31
Laravel
photosho, 2017-04-05 11:15:31

How to implement such a relationship in Laravel?

There is a table of materials (like movies) that can be related to each other. To describe this connection, I create a "Links" table, where there are 2 columns: "id_a" - the id of the material and "id_b" - the id of the linked material.
Let's say the structure is like this:

1 - 2
1 - 3
2 - 3
2 - 4

And I need to select from the "films" table all related materials. For example, for a material with id = 2. We see that you can select both the first column and the second.
The question is, how correct is such a structure and, perhaps, it needs to be implemented somehow differently? How is such a relationship implemented in Laravel?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
photosho, 2017-04-05
@photosho

So far done as follows. Added the "getLinks" method to the "Film" model:

public function getLinks() {
    $query = \DB::table('LINKS')->select('id_b')->where('id_a', '=', $this->id);
    $query = \DB::table('LINKS')->select('id_a')->where('id_b', '=', $this->id)
      ->union($query);
    $ids = $query->get();
    $buf = [];
    foreach ($ids as $id) {
      array_push($buf, $id->id_a);
    }
    $links = Film::whereIn('id', $buf)->get();
    $this->links = $links;
    return $this;
  }

So I make a choice from the database:
In general, everything works correctly, but ideas for simplifying the code (and most importantly, for optimizing) are still accepted.

R
Roman Igoshin, 2017-04-05
@MasterRO

Read the doc, all types of communication are supported in Laravel. In this case https://laravel.com/docs/5.4/eloquent-relationship...
And yes, you can make a model relationship to itself

D
Dmitry, 2017-04-13
@dlnsk

The usual many-to-many relationship, just the first and second tables are the same Movies table.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question