mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/compatibility/mongodb-laravel-integration
MIT License
6.99k stars 1.42k forks source link

Bug: Unable to embed model without a primary key #221

Closed 84564221 closed 10 years ago

84564221 commented 10 years ago

To create an Moloquent model for a legacy collection that has no primary key, simply set the protected primaryKey attribute to null.

This method does not work for EmbedsOne relations or EmbedsMany relations.

Example classes (User embedsOne Item):

<?php

class User extends Moloquent
{
    protected $collection = 'users';

    ...

    public function item()
    {
        return $this->embedsOne('Item');
    }
}

...

class Item extends Moloquent
{
        protected $primaryKey = null;

    ...
}

Result after performing $user->item()->save($item):

PHP Fatal error:  Maximum function nesting level of '100' reached, aborting! in /vendor/laravel/framework/src/Illuminate/Support/helpers.php on line 1004`
jenssegers commented 10 years ago

The embedded models use _id as default primary key as a way to identify the individual models. I don't really see why (or how) you would use embedded documents without _id.

84564221 commented 10 years ago

I'm looking for a solution, to reduce blowed up laravel model classes. WIth the DoctrineMongoDBBundle this was a common way for me, to embed objects {} within MongoDB documents.

What do you recommend to achieve this?

apollopy commented 9 years ago

You can try:

<?php

class User extends Moloquent
{
    protected $collection = 'users';

    ...

    public function item()
    {
        return $this->embedsOne('Item');
    }
}

...

class Item extends Moloquent
{
        protected $primaryKey = '__id';

    ...
}

and dont set __id

vacoup96 commented 4 years ago

Is there a solution for this? I'm currently working on a Meteor App that's not using ObjectID's. I'm migrating some things to laravel and now I'm encountering this issue. Setting no primaryKey variable does not working. Setting it to null also does not work. I think the problem is the setAttribute function. The whole function seems a strange to be honest.