Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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;
}
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question