我试图将以下传入数据存储到数据库中,除了一件事之外,它已成功存储。
当我输入$request->user()->posts()->save($answer);
时,除了post_id
之外,一切都保存得很好。
如果我用$post->answers()->save($answer);
替换它,除了user_id
之外,一切都保存得很好。
如何编辑save()方法以保存两者?
来自控制器的代码:
public function postAnswer(Request $request, $post_id)
{
$post = Post::where('id', $post_id)->first();
$body = $request['body'];
$pros = $request['pros'];
$cons = $request['cons'];
$answer = new Answer();
$answer->body = $body;
$answer->pros = $pros;
$answer->cons = $cons;
$post->answers()->save($answer);
答案 0 :(得分:1)
您一次尝试保存两个关系。 AFAIK,无法工作。
您需要先将帖子保存到用户,然后将答案保存到帖子中。
$request->user()->posts()->save($post);
$post->answers()->save($answer);
<强>更新强>
OP需要user_id
表中保存的answers
,因此我们也需要保存该关系。使用上面两行代码,$answer
并不知道有关用户的任何内容,只知道父$post
- 所以我们必须明确告诉$answer
它属于user
:
$request->user()->answers()->save($answer);
答案 1 :(得分:0)
您可能需要将此添加到模型中:
<强> post.php中:强>
protected $fillable = [
...
'post_id',
...
];
或必要的领域,祝你好运。