Laravel 超过 4 个表的关系

Laravel Relationships over 4 tables

我有一个 Laravel 关系问题。我有 4 个包含列的表...

tbl_applicants

applicant_id(key)

tbl_link_applicant_contact_history

tbl_contact_history

附件

class Applicant extends Model
{
    public function attachments() 
    {
      ...relationship
    }
}

如何与 Eloquent 建立关系以在申请人模型中获取附件?

你似乎有关系

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

为了简单起见,我假设 ContactHistoryAttachment 之间是一对一的,您可以从那里开始构建。然后你可以像这样建模你的模型:

编辑

您可以使用 Applicant 模型中的 hasManyThrough 通过 ContactHistory 检索许多 Attachments 模型。 Applicant 模型代码已更新为该方法。 documentation.

中的更多信息

申请人型号

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);
   }

}

联系人历史模型

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

所以现在对于 Applicant 您可以通过

获得所有关联的 Attachments
$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;
}

注意:我没有在这里显示 Attachment 模型,它也只是一个模型 class,您可以在其中与 ContactHistory 模型。希望这足以让您入门。