Many to Many relationship with "Link table" Laravel 9

211 Views Asked by At

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

There are 2 best solutions below

0
John Lobo On BEST ANSWER

use Many To Many Relationships

so in ProjectCases model add relationship like below

 public function services() {
        return $this->belongsToMany(Services::class, 'projectcases_to_services', 'projectcase_id', 'service_id');
    }

if you see param option for belongsToMany method

/**
     * Define a many-to-many relationship.
     *
     * @param  string  $related
     * @param  string|null  $table
     * @param  string|null  $foreignPivotKey
     * @param  string|null  $relatedPivotKey
     * @param  string|null  $parentKey
     * @param  string|null  $relatedKey
     * @param  string|null  $relation
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
                                  $parentKey = null, $relatedKey = null, $relation = null)
    {
    }

suggest 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

enter image description here

enter image description here

Images content used from Naming Convention Laravel

Also you can read here laravel-best-practices

2
jschpmr On

For a many-to-many relationship, you need to define a 'belongsToMany' relation on your ProjectCases model:

public function services()
{
    return $this->belongsToMany(Services::class, 'projectcases_to_services', 'projectcase_id', 'service_id');
}

You might also want to have a look at the explanations given here: https://laravel.com/docs/9.x/eloquent-relationships#many-to-many