laithalenooz's avatar

How to Define Relationships Between Models in Different Databases (MongoDB and MySQL) in Laravel?

Is it possible in Laravel to define a relationship between two models that reside in different databases, specifically when one model is stored in MongoDB and the other in MySQL? For example, I have a MySQL model that needs to load related data from a MongoDB model. Are there any recommended approaches or best practices to make this work smoothly, especially for eager loading or other types of relationships? Any guidance would be greatly appreciated!

0 likes
2 replies
vincent15000's avatar
Level 63

If you are working with relationships, it's not a good idea to use MongoDB which is a noSQL database.

About your question, I think that it's not possible to eager load exactly as in a pure Laravel / MySQL application. The query is created and sent to one database.

As you need to retrieve the datas from 2 different databases, you can first retrieve data from MySQL.

// MySQL
$books = Book::all();

And then retrieve the related data from MongoDB.

$categoriesIds = array_unique($books->pluck('category_id')->toArray());

// MongoDB
// but here with perhaps another syntax appropriated with a MongoDB ORM (not sure that Eloquent can retrieve datas from MongoDB, never tested)
$categories = Category::whereIn('id', $categoriesIds)->get();
1 like
laithalenooz's avatar

@vincent15000 The issue is that I'm forced to use MongoDB with SQL, we have logs stored in mongo with morph relation, I think it will cause a load if I go with this approach. Thank you for your answer!

1 like

Please or to participate in this conversation.