Daniel Valland
Daniel Valland

Reputation: 1107

Laravel Jensseger Mongodb belongsToMany returns empty array

I am trying to use a belongsToMany relation, in the following way: Model with belongsToMany relation:

namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class Notification extends \Jenssegers\Mongodb\Eloquent\Model
{
    use Notifiable, HasApiTokens;
    protected $collection = 'myDb.notifications';
    protected $fillable = [ ];
    protected $hidden = [  ];

    /**
    * List of involved users
    */
    public function participants()
    {
      return $this->belongsToMany(User::class);
    }
}

Creating a model:

$notification=new Notification();
....
$notification->participants()->attach(["5b13fb4393782d5e9010835d","5b13146f93782d29254c8cb2"]);
$notification->save();

Gives:

{
    ......
    "user_ids": [
        "5b13fb4393782d5e9010835d",
        "5b13146f93782d29254c8cb2"
    ],
    "updated_at": "2018-06-07 12:32:19",
    "created_at": "2018-06-07 12:32:19",
    "_id": "5b1925d393782d24b4514a16"
}

So ids are attached correctly, however, when I try to eager-load them with:

Notification::where('_id','=','5b1925d393782d24b4514a16')->with(['participants'])->get()

I get an empty array for the relation:

[
    {
        "_id": "5b1925d393782d24b4514a16",
        ....
        "updated_at": "2018-06-07 12:32:19",
        "created_at": "2018-06-07 12:32:19",
        "participants": []
    }
]

I have also verified that the given users actually exist, and should be "loadable", using:

User::whereIn('_id',["5b13fb4393782d5e9010835d","5b13146f93782d29254c8cb2"])->get()

Which gives the two users as expected....

Upvotes: 1

Views: 1364

Answers (2)

Traxo
Traxo

Reputation: 19002

Apparently we need two-way relationship, i.e. we need ids in BOTH tables.
We also need to set keys manually (or perhaps not, but I'm not sure what's right convention)

class Notification extends ...
{
    public function participants()
    {
      // NOTE: we set keys manually here:
      return $this->belongsToMany(User::class, null, 'notification_ids', 'user_ids');
    }
}

class User extends ...
{
    public function notifications()
    {
      // NOTE: we set keys manually here:
      return $this->belongsToMany(Notification::class, null, 'user_ids', 'notification_ids');
    }
}

Considering objects have following properties (fields):

User:

{
   ...
   notification_ids: []
}

Notification:

{
   ...
   user_ids: []
}

(both array of strings (ids))

Using attach should update both tables properly, for example:

$user->notifications()->attach($notification->id)

Upvotes: 1

Benjamin Barbé
Benjamin Barbé

Reputation: 271

I think there is a problem with the relation, can you try something like :

return $this->belongsToMany('App\User');

Upvotes: 0

Related Questions