skip to Main Content

I have table structures like this :

jobs

  • id
  • name

types

  • id
  • name

job_type (pivot table)

  • id
  • job_id
  • type_id

tasks

  • id
  • description

job_type_task (pivot table)

  • id
  • job_type_id
  • task_id

Notes :

  1. jobs has many types and vice versa
  2. job_type has many tasks and vice versa

My problem is with this table structures, How can I establish a relationship between ‘job’ and ‘tasks’ tables to access all tasks associated with a job?

I have tried many solution like using hasMany or hasManyThrough but none is working.

Should i change the table stuctures? or any solution to access tasks via job eloquent model?

2

Answers


  1. jobs:            id,  name
    jobs_types:  job_id, type_id
    types_tasks:         type_id, task_id
    tasks:                             id, description
    
    SELECT j.name
           k.description
        FROM jobs        AS j
        JOIN jobs_types  AS jy   ON jy.job_id = j.id
        JOIN types_tasks AS  yk  ON yk.type_id = jy.type_id
        JOIN tasks AS    AS   k  ON k.id = yk.task_id
        WHERE j.name = "XYZ"
    

    Note: There is no need for id in the mapping tables, but there is a need for indexes like:

    jobs_types:
        PRIMARY KEY(job_id, type_id)
        INDEX(type_id, job_id)
    

    (I do not know how to translate that into Lauravel.)

    Login or Signup to reply.
  2. there is no stock laravel relation for your case as your relation is not direct but through 2 entities and laravel only natively support 1 level down so you can check this package that might help you achieve what you need
    https://github.com/staudenmeir/eloquent-has-many-deep

    also there was a similar question that might be similar to your use case that helps creating a new custom relation since the stocked relations is not enough Custom Laravel Relations? and also this article explains it nicely https://stitcher.io/blog/laravel-custom-relation-classes

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search