laravelhas-many-through

Many to Many relationship with "Link table" Laravel 9


I have a Modal "ProjectCase" and I'm trying to link the Model "Services" to it.

My database structure is like this:

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?


Solution

  • 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