如何在 Laravel 中保存具有两个关系的模型?
我有3个型号:
Model user:
id
name
Model post:
id
text
user_id
Model comment:
id
message
post_id
user_id
创建评论:
#find post
$post = Post::find(1);
#Create comment and connect to post
$comment = $post->comments()->create($validated);
#How connect user?
如何连接用户?
文档中有很多示例,但没有这样的。
虽然
$model->relation()->create([])
创建了一个相关模型,但在关系的上下文中,没有办法为多个关系提供多个上下文。
因此,您需要自己添加 user_id
传递给 create
的数据
#find post
$validated = $request->validated();
$validated['user_id'] = $request->user()->id; // user performing the request
$post = Post::find(1);
#Create comment and connect to post
$comment = $post->comments()->create($validated);