我有这个表格
<form method='POST' action='/products/{{ $product->id }}/reviews'>
{{ csrf_field() }}
<div>
<textarea name = 'review' placeholder ='Post a review'>{{ old('review') }}</textarea>
</div>
<div>
<button type ='submit'>Save</button>
</div>
</form>
数据然后传递到我的控制器中的此函数
public function store(products $product)
{
$product->addReview(request('review'));
return back();
}
在我的产品模型中找到了addReview方法
public function addReview($review)
{
return reviews::create([
'product_id' => $this->id,
'review' => $review
]);
}
我认为问题出在这里'product_id' => $this->id,
一旦填写表格并提交,就没有数据添加到“ product_id”字段中。它不包含在任何发布数据中。
在您的评论模型中:
public function product() {
return $this->belongsTo(products::class);
}
我将其重命名为a,product
因为它是一个结果而不是多个结果。
然后在这里:
public function addReview($review)
{
return reviews::create([
'product_id' => $review->product->id,
'review' => $review
]);
}
甚至更好的是,如果要添加评论,则应选择产品而不是评论,因为要向产品添加评论,因此方法应类似于以下内容:
public function addReview($product)
{
$review = request('review');
return $product->reviews()->create([
'review' => $review
]);
}
编辑我看到你已经有这个..所以这个代码应该工作。如果reviews
表中有一product_id
列,则关系应该正确。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句