Laravel-mongodb: Creating a model without a _id?

Created on 21 Sep 2017  路  7Comments  路  Source: jenssegers/laravel-mongodb

Is it possible to create a model without a _id automatically created?

I'm looking to create an embedded model in another, and I don't want the subdocuments to have a _id key, as they already have other primary keys. As we unfortunately can't cast properties in embedded documents (i have a date in the subdocument), I want to use the embeds many functionality, but don't want to end up with a bunch of useless ids attached.

I looked at primaryKey, but that doesn't seem to do anything.

bug

All 7 comments

Do you test using protected $primaryKey = 'your_key_field'; ?

Why do you need the sub-documents to extend the Eloquent model?

I don't really follow the question, @lindelius. I'm not looking to extend the model, I'm trying to use the embedsMany functionality, but trying to do it without creating new _ids, as the subdocuments don't need them. As I said, since we can't cast properties in embedded documents, I figured embedding models is the best option, unless there's another way I'm not thinking of?

Do your sub-documents also live in their own collection, or is the data just saved on the parent models?

If yes (they have their own collection), then you're going to need to keep the IDs to be able to keep the normalized data up-to-date with the original document.

If no, then there's no reason to use Eloquent models to represent the sub-documents and the embed-methods to add them to the parent model.

That was my first plan of attack @lindelius, and what I've been doing so far. But like I mentioned in my reply, my issue is that we can't cast the types of data in subdocuments, so I was wondering if there was a way to use embed so that I could do things like cast dates in subdocuments rather than have to write a mutator for each subdocument I may create.

I came across this scenario and I could solve it by declaring the following in the Embedded model class:

    public $incrementing = false;
    protected $primaryKey = null;

I tried having only the $incrementing attribute set to false but that alone doesn't seem to be enough, it's necessary to set $primaryKey as null as well. I only tried with EmbedsOne, but I guess it's the same for EmbedsMany.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sebastiaanluca picture sebastiaanluca  路  3Comments

bastiendonjon picture bastiendonjon  路  3Comments

sanjay1688 picture sanjay1688  路  3Comments

kschethan picture kschethan  路  3Comments

BlakeGardner picture BlakeGardner  路  3Comments