嗨,我有2个具有关联关系的模型-用户和聊天。
模型聊天具有一个 id(uuid)字段作为主键:
public $primaryKey = 'id';
public $keyType = 'string';
public $incrementing = false;
public function users()
{
return $this->belongsToMany(User::class, 'chat_user', 'chat_id', 'user_id');
}
用户:
public function chats()
{
return $this->belongsToMany(Chats::class, 'chat_user', 'user_id', 'chat_id');
}
数据透视表:
id | chat_id(uuid)| user_id(int)
当我尝试将用户与聊天同步时,因为我的chat_id为空,所以没有违反null的行为:
失败行包含(1,null,1)
--------------------------------- ^
向聊天模型添加protected $casts = ['id' => 'string'];
不能解决问题。我在做什么错了?
更新
我的商店方法:
$chat = $this->chatRepository->create([
'name' => $request->name,
'creator_id' => Auth::id(),
]); // also, chat succesfully created at this step but if I'm checking dd($chat) - it doesnt contain 'id' in attributes array...
$memberIds = $this->userRepository
->findWhereIn('email', collect($request->members)->pluck('email')->toArray(), ['id']);
$chat->users()->sync($memberIds); < error at this step
答案 0 :(得分:0)
由于$ chat没有id
属性(这是问题所在),并且您已经修改了演员表系统,请尝试使用-> save()方法保存
$this->chatRepository = new ChatRepository();
$this->chatRepository->name = $request->name;
$this->creator_id = Auth::id();
$this->save();
或者,再次致电聊天。
$chat_id = $this->chatRepository->create([
'name' => $request->name,
'creator_id' => Auth::id(),
])->id;
$chat = $this->chatRepository::find($chat_id);