user11710915:
私は私が見た、一度だけレビュー(率)製品にユーザーをしたい、これをしてみましたが、私はエラーになってるObject of class Illuminate\Database\Eloquent\Collection could not be converted to int
私は、ユーザーが一度製品をレビューすることができるようになりますようにこの問題を解決する方法を。
Product.php
public function reviews()
{
return $this->hasMany(ProductReview::class);
}
public function currentUserHasSubmittedReview(){
$countOfReviews = $this->reviews()
->where('user_id', Auth::user()->id)
->where('product_id', $this->id)
->get();
return ($countOfReviews > 1 ? true : false); //Error comes from this line
}
ProductReview.php
public function product()
{
return $this->belongsTo('App\Product');
}
ブレードファイル
@foreach($products as $product)
@if ($product->currentUserHasSubmittedReview() == false )
<a " href="#openModal-about">Write review</a>
@else
@endif
@endforeach
RWD:
$countOfReviews
ですCollection
が、あなたが使用して整数のように扱うしようとしています> 1
。> 1
以上の1ではなくがある場合が存在する場合にのみtrueを返します。
これを回避する一つの方法は、使用することですexists()
代わりにget()
、クエリで:
public function currentUserHasSubmittedReview()
{
return $this->reviews()
->where('user_id', Auth::user()->id)
->where('product_id', $this->id)
->exists();
}
データベースは、より多くのリフティングのやっている、あなたは事実後にそれらをカウントするだけで、複数のコレクションインスタンスをロードする必要がいないので、上記は、同様に、より効率的になります。