Skip to content

Fix BelongsToMany Relation to Support Array Foreign Keys in Laravel MongoDB #3310

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 4 commits into
base: 5.x
Choose a base branch
from

Conversation

peymanaslani70
Copy link

@peymanaslani70 peymanaslani70 commented Mar 6, 2025

🚀 What’s in This PR?

This PR fixes the BelongsToMany relationship to support array-based foreign keys, allowing multiple related ObjectIds to be stored in a single field.

🐞 The Issue

  • Previously, BelongsToMany expected foreign keys to be a single value, causing issues when an array was used.
  • This resulted in errors like Illegal offset type when working with MongoDB.

🔍 Issue Reference
Fixes [#3015]

🔧 Changes Made

✅ Updated attach() in BelongsToMany.php to store ObjectIds as an array instead of a single value.
✅ Modified buildDictionary() to correctly handle arrays when resolving relationships.
✅ Added a new unit test: testBelongsToManyRelationSupportsArrayForeignKeys (in tests/RelationsTest.php).

  • Ensures that array-based foreign keys work as expected.
  • Confirms that relationships retrieve the correct data.

🧪 How to Test It?

  1. Run the tests with:
    vendor/bin/phpunit tests/RelationsTest.php
  2. All tests should pass ✅

📜 Documentation Update Checklist

✔️ Updated Many-to-Many Relationship section in the docs.
✔️ Explained how to use array-based foreign keys with BelongsToMany().
✔️ Added an example showing how to define relationships with an array field.

Checklist

  • Add tests and ensure they pass
  • Updated Many-to-Many Relationship section in the docs.

@peymanaslani70 peymanaslani70 requested review from a team as code owners March 6, 2025 10:35
@github-actions github-actions bot added the docs label Mar 6, 2025
@jmikola jmikola requested review from GromNaN and removed request for jmikola and norareidy March 6, 2025 16:12
@GromNaN GromNaN added feature and removed docs labels Mar 6, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants