A
A
alestro2016-10-02 19:44:14
Laravel
alestro, 2016-10-02 19:44:14

Relationships in Laravel. How to be?

Is it possible to implement communication in the context of one model. Suppose there is a Game model and the platforms table needs to organize a many-to-many relationship, how can you place the platforms array in the model property of the same name without creating the Platforms model.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tesla, 2016-10-03
@Tesla

You can do something like this:

public function platforms() {
  return DB::table('game_platforms')
    ->join('platforms', 'platforms.id', '=', 'game_platforms.platform_id')
    ->where('game_platforms.game_id', '=', $this->id)
    ->get();
}

But in fact, you will be duplicating and cycling code from model to model wherever data from the platforms table is needed. In addition, you lose lazy loading and a bunch of useful Eloquent little things.
In short, it is possible, but is it necessary?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question