Laravel Jensseger Mongodb belongsToMany returns empty array

拟墨画扇 提交于 2019-12-02 18:37:36

问题


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


回答1:


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

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



回答2:


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)



来源:https://stackoverflow.com/questions/50741423/laravel-jensseger-mongodb-belongstomany-returns-empty-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!