mongodblaraveljenssegers-mongodb

MongoDB & MySQL relationships in jenssegers/laravel-mongodb


Let's begin with some plain code. I have two following models. First is using MySQL:

class Phrase extends \Eloquent {

    public function positions()
    {
         return $this->hasMany('Position');
    }

    public function getIdAttribute($id)
    {
        return (int) $id;
    }
}

and second is using MongoDB:

use Jenssegers\Mongodb\Model as Eloquent;

class Position extends Eloquent {

    protected $collection = 'positions';
    protected $connection = 'mongodb';

    public function phrase()
    {
        return $this->belongsTo('Phrase');
    }
}

In my controller I want to get phrase positions:

Phrase::find(1)->positions

which is generating query

positions.find({"positions.phrase_id":1}, [])

instead of

positions.find({"phrase_id":1}, [])

How I can fix it? The problem is inside HasMany method (http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Model.html#_hasMany).


Solution

  • I managed to get the functionality by creating my own function inside the model

    class Phrase extends \Eloquent {
    
        public function positions()
        {
            return Position::where('phrase_id', '=', (int) $this->id)->get();
            return $this->hasMany('Position');
        }
    }
    
    
    $positions = Phrase::find(1)->positions();
    

    Anyway, this solution is not a great replacement, because it's breaking convention. Third programmers may not know how to use this relationship.