Laravel中如何通过Eloquent获取中间表外键关联的修订集合
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
belongsToManybecause eachMemocan be associated with multipleForeignCitizenRevisionentries. - The parameters break down to:
- The target model (
ForeignCitizenRevision::class) - The name of the pivot table connecting
Memoto the revision records - The foreign key for
Memoon the pivot table (memo_id) - The foreign key for
ForeignCitizenRevisionon the pivot table (foreign_citizen_revision_id)
- The target model (
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

