How to cast ObjectId in Model, instead in where condition #2752
Replies: 2 comments 2 replies
-
It's working fine for me. $stringId = (string) (new ObjectId()); Client::query()->create(['cclient_id' => $stringId, 'name' => 'Young Gerald']); Client::query()->where('cclient_id', $stringId)->first(); What version you are using? |
Beta Was this translation helpful? Give feedback.
2 replies
-
When querying the set wont be called, for solution, we just need to modify $objectId= $this->convertToObjectId($objectIdString); //Supports conversion of string, array of string or collection of string Client::query()->create(['cclient_id' => $objectId, 'name' => 'Young Gerald']); Client::query()->where('cclient_id', $objectId)->first(); No checking of its valid objectid string since most of the source of objectid is from the collection itself <?php namespace App\Traits; use MongoDB\BSON\ObjectId; trait ObjectIdConversion { public function convertToObjectId($value) { // Check if the value is an instance of ObjectId and skip conversion if ($value instanceof ObjectId) { return $value; } // Check if the value is a Collection if ($value instanceof \Illuminate\Support\Collection) { // Convert Collection to an array $value = $value->toArray(); } // Check if the value is an array if (is_array($value)) { foreach ($value as $key => $item) { // Recursively call the function if the item is an array $value[$key] = $this->convertToObjectId($item); } return $value; } else { // Convert the value to an ObjectId return new ObjectId($value); } } public function convertObjectIdToString($value) { if ($value instanceof \Illuminate\Support\Collection) { // Convert Collection to an array $value = $value->toArray(); } // Check if the value is an array if (is_array($value)) { foreach ($value as $key => $item) { // Recursively call the function if the item is an array $value[$key] = (string) $item; } return $value; } else { // Convert the value to an ObjectId return (string) $value; } } } |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Is this correct? Its not working. but wrapping it
not working
this works
WorkoutLogs::where('ruleType', 'Vitals')->where('createdBy', new BSONObjectId('5be9ce7b3de6dd77db832950'))->orderBy('createdAt', 'desc')->paginate(10);
Beta Was this translation helpful? Give feedback.
All reactions