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.
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:
<?php namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Employee extends Eloquent {
protected $collection = 'employee';
protected $primaryKey = '_id';
public function tasks()
{
return $this->belongsToMany('App\Models\Task');
}
}
<?php namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Task extends Eloquent {
protected $collection = 'task';
protected $primaryKey = '_id';
public function employees()
{
return $this->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());
Yep, you need to use belongsToMany instead of hasMany in this case...