我正在尝试使用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()
这给了两个用户按预期......
答案 0 :(得分:0)
我认为这种关系存在问题,您可以尝试以下方式:
return $this->belongsToMany('App\User');
答案 1 :(得分:0)
显然,我们需要双向关系,即我们都需要两个表中的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: []
}
(两个字符串(id)的数组)
使用附件应该正确更新两个表,例如:
$user->notifications()->attach($notification->id)