Search code examples
phplaravellumen

Laravel Relationships over 4 tables


i have a Laravel relationship Problem. I have 4 tables with columns...

tbl_applicants

applicant_id(key)

tbl_link_applicant_contact_history

  • link_id(key)
  • applicant_id
  • contact_history_id

tbl_contact_history

  • id(key)

attachments

  • id(key)
  • contact_history_id(foreign_key from tbl_contact history)
  • filename
class Applicant extends Model
{
    public function attachments() 
    {
      ...relationship
    }
}

How can I build relationship with Eloquent to get attachments in Applicant model?


Solution

  • You seem to have the relationships

    Applicant<---many-to-many--->ContactHistory<---one-to-one/one-to-many--->Attachment
    

    I am assuming one-to-one between ContactHistory and Attachment for simplicity and you can build up from there. Then you can model your models like:

    EDIT

    You can use the hasManyThrough in the Applicant Model in to retrieve many Attachments through ContactHistory Model. The Applicant Model code is updated with the method. More information in the documentation.

    Applicant Model

    class Applicant extends Model
    {
        /**
         * The contacthistories that belong to the applicant.
         */
    
        public function contacthistories() 
        {
          return $this->belongsToMany(ContactHistory::class);
        }
    
    
       /**
        * Get all of the attachments for the applicant.
       */
       public function attachments()
       {
          return $this->hasManyThrough(ContactHistory::class, Attachment::class);
       }
    
    }
    

    ContactHistory Model

    class ContactHistory extends Model
    {
        /**
         * Get the attachment for the contact history.
         */
        public function attachment()
        {
            return $this->hasOne(Attachment::class);
        }
    }
    

    So now for an Applicant you can get all the associated Attachments by

    $applicant = Applicant::find(1);
    
    // Loop through all the contacthistories of an applicant, where each contacthistory $ch has an attachment.
    
    foreach ($applicant->contacthistories as $ch) {
            $ch->attachment;
    }
    

    Note: I have not shown here the Attachment model which is also simply a model class where you can have inverse relationship to the ContactHistory model. Hope this gives you enough to get started.