Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Jenssegers MongoDb Relationships not working?

I'm trying to setup some simple favoriting for my app using Laravel/Jenssegers MongoDB

I have two models:

class Item {

    public function favorites()
    {
       return $this->hasMany('App\Models\User', 'favorites');
    }
}

class User {

    public function favorites()
    {
       return $this->hasMany('App\Models\Item', 'favorites');
    }
}

So an item can have many users and a user can have many items or "favorites".

When I try to run a simple query like:

Item::with('favorites')->get();

The relationship for favorites is there but an empty array.

The favorites table is simple and just has three columns:

_id, item_id, user_id

I've also tried using embedsMany with no luck:

return $this->embedsMany('App\Models\User', 'favorites');

I've also tried every combination of parameters.

return $this->embedsMany('App\Models\User', 'favorites', 'building_id', 'user_id');
return $this->embedsMany('App\Models\User', 'favorites', 'user_id', 'building_id');
return $this->hasMany('App\Models\User', 'favorites', 'building_id', 'user_id');
return $this->hasMany('App\Models\User', 'favorites', 'user_id', 'building_id');

Strange results when using:

return $this->hasMany('App\Models\User', 'favorites', 'building_id', 'user_id');

Only in this situation it returns ALL users, even though favorites has only one record.

Also trying to debug using getQueryLog just gives me an empty array at all times.

print_r(\DB::connection('mongodb')->getQueryLog());

I've done this using mysql and have never had issues. So not really sure where the issues are coming from.

like image 577
Rob Avatar asked Apr 06 '16 05:04

Rob


1 Answers

Can you try these instead, I know its the same thing but might do the trick :

use App\User;
use App\Item;

class Item {

    public function favorites()
    {
       return $this->hasMany('User');
    }
}

class User {

    public function favorites()
    {
       return $this->hasMany('Item');
    }
}

class Favourite {

        public function users()
        {
           return $this->belongsTo('User');
        }

        public function items()
        {
           return $this->belongsTo('Item');
        }
    }

Also add inverse of the above relations like: belongsTo. and try this query then :

//Just for testing purpose, if raw query returns right result
$items = DB::table('items')
->join('favorites','items.id','=','favorites.id')
->get();
like image 64
Murlidhar Fichadia Avatar answered Oct 24 '22 06:10

Murlidhar Fichadia