I have a Modal "ProjectCase" and I’m trying to link the Model "Services" to it.
My database structure is like this:
- ProjectCases
- id
- title
- projectcases_to_services
- projectcase_id
- service_id
- Services
- id
- title
Now I’m trying to make a link between the two and be able to get all the services through the "ProjectCase" model
I’ve figured out that i should create a function, which uses the hasManyThrough function.
I’ve tried the following:
public function services() {
return $this->hasManyThrough(Services::class, cases_to_services::class, 'case_id', 'id', 'id', 'service_id');
}
But this returns all the services.
What am I missing?
2
Answers
use Many To Many Relationships
so in
ProjectCases
model add relationship like belowif you see param option for
belongsToMany
methodsuggest you to follow laravel naming conventions for models and database table.So that you can keep code clean
Some Naming Convention best practices for laravel
Images content used from Naming Convention Laravel
Also you can read here laravel-best-practices
For a many-to-many relationship, you need to define a ‘belongsToMany’ relation on your ProjectCases model:
You might also want to have a look at the explanations given here:
https://laravel.com/docs/9.x/eloquent-relationships#many-to-many