hasMany relationship issue in Laravel 5.3 + MongoDB library 'jenssegers/laravel-mongodb'

前端 未结 2 1570
天命终不由人
天命终不由人 2021-01-22 02:57

I am using MongoDB library in Laravel 5.3. I have two collections in MongoDB and I want to make a hasMany relation b/w them.

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-22 03:18

    in Mongo Eloquent when creating Many to Many relationships you dont need to have a pivot table, thats SQL mindset, in mongo-eloquent many to many relations the foreign keys are stored in arrays. So the models should look like this:

    belongsToMany('App\Models\Task');
        }
    }
    
    
    
    
    
    belongsToMany('App\Models\Employee');
        }
    }  
    

    Also you should load the relations before trying to retrieve them

     $employee= Employee::with('tasks')->find('586ca8c71a72cb07a681566d')->tasks;
    

    You can save the relation the same way you do it in the hasMany relation

    $employee->tasks()->save(new Task());
    

提交回复
热议问题