1

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).

Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
Mateusz Nowak
  • 4,021
  • 2
  • 25
  • 37

2 Answers2

2

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.

giannis christofakis
  • 8,201
  • 4
  • 54
  • 65
Mateusz Nowak
  • 4,021
  • 2
  • 25
  • 37
1

use this trait in both models and u can use basic relationships

use Jenssegers\Mongodb\Eloquent\HybridRelations;

class User extends Model 
{
   protected $connection = "mysql" ;

   use HybridRelations ;

}

class Orders extends Model 
{
   protected $connection = "mongo" ;

   use HybridRelations ;
}