mongodb - 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()
这给了两个用户的预期....
解决方案
显然我们需要双向关系,即我们需要两个表中的 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)
推荐阅读
- c# - PostSharp Logging 添加 >>> 和 <<< 到方法进入/退出日志条目
- javascript - 如何使用 Fetch 变量 - Javascript
- google-api - 将 Google API 访问权限限制为单个或一组用户,而不是对您的服务帐户的域范围权限
- c++ - 我是否使用了正确的不失真例程?照片是广角还是鱼眼?
- python - Python Regex.split text + 将每个拆分导出为 .txt,每个拆分单词作为文件名导出到指定文件夹
- python - 只有当它们通过熊猫在下一次迭代中重复时,我才能删除重复项
- c++ - 分配一个仅作为抽象类指针的对象
- docker - 如何从给定的 docker 网络内部连接到 L2TP/Ipsec 后面的主机?
- python - Pandas:如何为数据框中的每个重复行创建一个计数器
- flutter - 空安全迁移后如何解决库/包之间的冲突?