laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

[HasOne from one model to an embedded one]

Open lbrutti opened this issue 3 years ago • 3 comments

Is your feature request related to a problem?

I have three models, say: Model A Model B Model C

Model B embeds Model C in an array and Model A has references to both B and C primary keys.

While I can easily define an hasOne relation from A to B, i can't define it from A to C.

Here's some snippets of what I tried so far:

modelA = ['model_b_id'=>'xxx', 'model_c_id'=>'yyy'];
modelB = [
        'b_id'=>'xxx', 'model_cs'=>[
            ['c_id'=>'yyy', 'other_stuff'=>123], //model C instances are embedded and do not live outside model A collection
            ['c_id'=>'zzz', 'other_stuff'=>456]
        ]
    ];

class ModelA extends Eloquent {
    public function model_b(){
        return $this->hasOne(ModelB::class, 'b_id', 'model_b_id');
    }

    //this doesn't work
    public function model_c(){
        return $this->hasOne(ModelC::class, 'c_id', 'model_c_id');
    }

    //this doesn't work
    public function model_c(){
        return $this->hasOneTrough(ModelC::class, ModelB::class, 'c_id', 'b_id', 'model_c_id', 'model_b_id');
    }

    //works but it's not a relation
    public function model_c(){
        return $this->model_b->model_cs->where('c_id', 'model_c_id');
    }
}
class ModelB extends Eloquent {
    public function model_cs(){
        return $this->embedsMany(ModelC::class);
    }
}

thanks for any suggestion

lbrutti avatar Jun 09 '22 12:06 lbrutti

Hi @lbrutti, you can try this package!

SanaviaNicolas avatar Jun 13 '22 14:06 SanaviaNicolas

Hi @lbrutti, you can try this package!

hi! @SanaviaNicolas , thanks, but i guess that is a replacement for Jenssegers' one, isn't it?

lbrutti avatar Jun 13 '22 14:06 lbrutti

@lbrutti Laravel Mongo Auto Sync is a wrapper of jenssegers/laravel-mongodb and it has been created to provide a better support for MongoDB relationships and to resolve bugs that will never be solved on this project, in fact in the new version 4 embeds relationships will be removed.

SanaviaNicolas avatar Jun 13 '22 15:06 SanaviaNicolas