lundi 4 mars 2019

3 models relationship in Laravel 5

I have 3 Models.

  • Project {id, name}
  • Platform {id, name}
  • Version {id, value}

One Project can have multiple Platforms and each Platform can have multiple Versions within a Project. I have the following table which relates the models:

enter image description here

As you can see Project 6 has versions 1 and 3 on platform 1, while Project 8 has versions 1 and 2 on the same platform.

I want to get all Projects' Platforms and versions of those Platforms depending on the Project.

For example, I'd like to do

App\Project::find(6)->platform()->with('version')->get();

and get only versions with ids of 1 and 3 on my version collection of platform 1 of this project.

This is what I have in Project Model:

public function platform()
{
    return $this->belongsToMany('App\Platform')->withPivot('version_id')->distinct();
}

This is what I have in Platform Model:

public function version()
{
    return $this->belongsToMany('App\Version', 'platform_project')->distinct();
}

Could you please help me figure out the best way to achieve the desired result?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire