コレクションにはLaravelをintに変換することができませんでした

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();
}

データベースは、より多くのリフティングのやっている、あなたは事実後にそれらをカウントするだけで、複数のコレクションインスタンスをロードする必要がいないので、上記は、同様に、より効率的になります。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=303116&siteId=1