Laravel Jensseger Mongodb includesToMany返回空数组 [英] Laravel Jensseger Mongodb belongsToMany returns empty array
问题描述
我正在尝试通过以下方式使用belongsToMany关系: 带有belongsToMany关系的模型:
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);
}
}
创建模型:
$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时,它们会正确附加:
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....
推荐答案
显然,我们需要双向关系,即我们都需要两个表中的ID.
我们还需要手动设置键(或者可能不是,但是我不确定什么是正确的约定)
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):
用户:
{
...
notification_ids: []
}
通知:
{
...
user_ids: []
}
(两个字符串(id)的数组)
(both array of strings (ids))
使用附件应正确更新两个表,例如:
Using attach should update both tables properly, for example:
$user->notifications()->attach($notification->id)
这篇关于Laravel Jensseger Mongodb includesToMany返回空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!