2

I'm having trouble mapping relations in Doctrine ODM, because they're not using the _id field. I'm currently building a symfony app using the Doctrine Mongo ODM. The app is being built on top of a legacy Mongo schema (the database is already in production) and I can't change that schema.

In the current schema, a something_id field in each document is auto-generated, and these are used as the relation. To take an example of the post->comment:

//Post
{
    "_id" : ObjectId("abcd1234..."),
    "title" : "Test title 1",
    "content" : "lkjlkjlkjlkjl",
    "date_added" : NumberLong(1400000000),
    "post_id" : NumberLong(123456789012345) //this is manually generated
}

The post_id field is automatically generated (and unique and is used as the index) and the corresponding comment:

//Comment
{
    "_id" : ObjectId("abcd1234..."),
    "title" : "Test comment 1",
    "comment" : "lkjlkjlkjlkjl",
    "date_added" : NumberLong(1400000000),
    "comment_id" : NumberLong(123456789012345), //this is manually generated
    "post_id" : NumberLong(123456789012345) //this is the 'Foreign Key'
}

In the above example, the comment document references the post document by its manually generated post_id field, rather than _id or a dbref.

I don't know why it was built this way instead of using _id or dbref but I can't change it.

I've been trying to map this in Doctrine. I can't seem to do it and can't seem to see anything in the documentation about it. I had thought a 'simple' reference would do it as follows, but it doesn't seem to work:

 /**
 * @MongoDB\ReferenceMany(
 *     targetDocument="Comment", 
 *     mappedBy="postId", 
 *     simple=true)
 */
protected $comments = array(); 

Is it possible to do what I am trying? i.e. to have relations based on a non _id field?

Thanks in advance

applestump
  • 21
  • 1
  • I'm afraid it's not possible, ODM works with `_id` fields since they are always present and unique. Also there's no way to configure "foreign key" for references. – malarzm May 22 '16 at 12:32

0 Answers0