In Yii2 with MongoDB, relational searching is not as straightforward as it is in traditional relational databases like MySQL. MongoDB is a NoSQL database, and its design is different from SQL databases in terms of data modeling and querying.

In MongoDB, there are no native SQL-like joins to perform relational searches as you would in a traditional SQL database. Instead, you typically design your data schema to embed related data or use manual references between collections.

Here are two common approaches to handle relational searching in Yii2 with MongoDB:

  1. Embedded Documents: In this approach, you embed related data directly within a document. For example, if you have a "users" collection and a "posts" collection, you could embed the posts within the user document. Then, you can perform searches on the "users" collection and retrieve their related posts directly.

  2. Manual References: In this approach, you store references to related documents using an identifier, usually the MongoDB ObjectId, in one collection that points to another collection. For example, in the "users" collection, you could have a field that stores the ObjectIds of the related "posts" collection. Then, you can use these references to query related data.

Let's briefly explore both approaches:

Embedded Documents Example:

Suppose you have a "users" collection with embedded "posts":

php
// User model class User extends \yii\mongodb\ActiveRecord { public static function collectionName() { return 'users'; } public function attributes() { return [ '_id', 'username', 'email', 'posts', // Embedded posts ]; } // Other methods and validations... }

To search for users and their related posts, you can use Yii2's MongoDB query methods, like find() and where():

php
$users = User::find()->where(['username' => 'john'])->all(); foreach ($users as $user) { foreach ($user->posts as $post) { // Process each post } }

Manual References Example:

Suppose you have a "users" collection and a separate "posts" collection, and the "users" collection contains references to posts using ObjectIds:

php
// User model class User extends \yii\mongodb\ActiveRecord { public static function collectionName() { return 'users'; } public function attributes() { return [ '_id', 'username', 'email', 'postIds', // Array of ObjectIds referencing posts ]; } // Other methods and validations... }

To search for users and retrieve their related posts, you can perform queries and use in to match the ObjectIds:

php
$user = User::find()->where(['username' => 'john'])->one(); if ($user !== null) { $postIds = $user->postIds; $posts = Post::find()->where(['_id' => ['$in' => $postIds]])->all(); // Process the related posts }

Remember that the optimal approach depends on your specific use case and the nature of your data. You should carefully design your data schema in MongoDB to suit the types of queries you need to perform frequently.

Have questions or queries?
Get in Touch