【问题标题】:Laravel with mongodb belongsToMany syncLaravel 与 mongodb 的 belongsToMany 同步
【发布时间】:2015-05-07 21:18:08
【问题描述】:

我正在使用 Laravel 4 和 mongodb 2.0.4 module 我有 User 和 Role 类,我试图将 belongsToMany 关系与附加、分离和同步方法一起使用

用户类

public function roles()
{
    return $this->belongsToMany('Role', null, 'user_ids', 'role_ids');
}

角色类

public function users()
{
    return $this->belongsToMany('User', null, 'role_ids', 'user_ids'
}

当我运行附加方法时

$user = User::find($id);
$user->roles()->attach(array($role_id));

mongodb 生成其中一个查询错误(或没有?)

user.update({"_id":{"$id":"54f8d7802228d5e42b000036"}},{"$addToSet":{"role_ds":{"$each":["54f8d7b02228d5e42b000037"]}}},{"multiple":true})

role.update({"_id":["54f8d7b02228d5e42b000037"]},{"$addToSet":{"user_ids":{"$each":["54f8d7802228d5e42b000036"]}}},{"multiple":true})

用户集合已更新,但角色集合保持不变。 它应该生成这样的查询吗?

role.update({"_id":{"$id":"54f8d7b02228d5e42b000037"}},{"$addToSet":{"user_ids":{"$each":["54f8d7802228d5e42b000036"]}}},{"multiple":true})

附加和分离方法都存在此问题。只有同步才能正确运行。但前提是只有一个元素。如果您在多个元素上运行同步,则其中一个集合由于查询错误而始终保持不变。

是我遗漏了什么还是这种关系真的有问题? 任何帮助都会很棒。谢谢

【问题讨论】:

  • 看起来有问题。您是否准备提交一个比较示例,其中一个关系端是belongsToMany(),另一端是hasMany()。缺少ObjectId 打字令人不安。列表转换处理也是如此。我很想知道我提到的测试用例是否会产生相似或不同的结果。
  • 我有一个类似的结构。使用 $user->roles 时,我会返回一个 id 数组。我想拥有这些对象。是我的配置错误还是这是正常行为?

标签: mongodb laravel laravel-4


【解决方案1】:

替换

$user->roles()->attach(array($role_id));

$user->roles()->attach($role_id);

如果你的参数不是数组,你必须使用attach 方法。 sync 方法只接受数组作为参数。 Here 是对它们的一个很好的解释。希望对你有用。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-07-12
  • 2017-01-20
  • 2015-03-26
  • 2021-01-08
  • 2019-05-31
  • 2015-01-16
  • 2018-01-31
  • 1970-01-01
相关资源
最近更新 更多