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

前端 未结 2 1563
天命终不由人
天命终不由人 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:

    <?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());
    
    0 讨论(0)
  • 2021-01-22 03:34

    Yep, you need to use belongsToMany instead of hasMany in this case...

    0 讨论(0)
提交回复
热议问题