You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何通过Eloquent获取中间表外键关联的修订集合

Solution: Add a Direct Eloquent Relationship for Foreign Citizen Revisions

Hey there! Let's figure out how to get those Foreign Citizen Revisions directly via your Memo model using Eloquent—no manual DB queries needed.

The key here is leveraging the existing pivot table (that connects Memo and ForeignCitizen) which already stores the foreign_citizen_revision_id. We can define a new relationship on the Memo model that directly links to ForeignCitizenRevision through this pivot table.

Step 1: Define the Relationship in Your Memo Model

Add this method to your Memo class:

public function foreignCitizenRevisions()
{
    // Replace 'memo_foreign_citizen' with your actual pivot table name if it's different
    return $this->belongsToMany(ForeignCitizenRevision::class, 'memo_foreign_citizen', 'memo_id', 'foreign_citizen_revision_id')
        ->withPivot('foreign_citizen_id') // Optional: Include if you need the linked Foreign Citizen ID
        ->withTrashed(); // Match the withTrashed() from your existing foreignCitizens() relationship
}

How This Works

  • We use belongsToMany because each Memo can be associated with multiple ForeignCitizenRevision entries.
  • The parameters break down to:
    1. The target model (ForeignCitizenRevision::class)
    2. The name of the pivot table connecting Memo to the revision records
    3. The foreign key for Memo on the pivot table (memo_id)
    4. The foreign key for ForeignCitizenRevision on the pivot table (foreign_citizen_revision_id)

Optional: Include Linked Foreign Citizen Data

If you want to load the associated ForeignCitizen along with each revision, first make sure your ForeignCitizenRevision model has this relationship:

// In ForeignCitizenRevision.php
public function foreignCitizen()
{
    return $this->belongsTo(ForeignCitizen::class);
}

Then update the foreignCitizenRevisions method in Memo to eager load this relationship automatically:

public function foreignCitizenRevisions()
{
    return $this->belongsToMany(ForeignCitizenRevision::class, 'memo_foreign_citizen', 'memo_id', 'foreign_citizen_revision_id')
        ->withPivot('foreign_citizen_id')
        ->withTrashed()
        ->with('foreignCitizen'); // Eager load the linked Foreign Citizen
}

Usage

Now you can fetch the revisions exactly like you wanted:

$memo = Memo::find($memoId);
$revisions = $memo->foreignCitizenRevisions; // Returns a collection of ForeignCitizenRevision models

This will handle all the underlying query logic for you, keeping your code clean and aligned with Eloquent's best practices.

内容的提问来源于stack exchange,提问作者Victor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:21:23