首页 > 解决方案 > Laravel Jensseger Mongodb belongsToMany 返回空数组

问题描述

我正在尝试通过以下方式使用belongsToMany关系:具有belongsToMany关系的模型:

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);
    }
}

创建模型:

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

给出:

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

但是,当我尝试使用以下方法急切加载它们时,ID 已正确附加:

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

我得到一个空数组的关系:

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

我还验证了给定的用户确实存在,并且应该是“可加载的”,使用:

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

这给了两个用户的预期....

标签: mongodblaraveljenssegers-mongodb

解决方案


显然我们需要双向关系,即我们需要两个表中的 id。
我们还需要手动设置键(或者可能不需要,但我不确定什么是正确的约定)

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');
    }
}

考虑到对象具有以下属性(字段):

用户:

{
   ...
   notification_ids: []
}

通知:

{
   ...
   user_ids: []
}

(两个字符串数组(ids))

使用 attach 应该正确更新两个表,例如:

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


推荐阅读