【问题标题】:Collection could not be converted to int Laravel集合无法转换为 int Laravel
【发布时间】:2020-03-14 09:36:15
【问题描述】:

我希望用户只对产品进行一次评论(评分),我看到 this 并尝试过,但我收到错误 Object of class Illuminate\Database\Eloquent\Collection could not be converted to int 我该如何解决这个问题,以便用户能够评论产品一次。

产品.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

【问题讨论】:

  • $countOfReviews &gt; 1更改为$countOfReviews-&gt;count()

标签: php laravel laravel-5 eloquent


【解决方案1】:

$countOfReviewsCollection,但您正试图通过使用 &gt; 1 将其视为整数。 &gt; 1 只会在超过 1 个而不是存在一个时返回 true。

解决此问题的一种方法是在查询中使用exists() 而不是get()

public function currentUserHasSubmittedReview()
{
    return $this->reviews()
        ->where('user_id', Auth::user()->id)
        ->where('product_id', $this->id)
        ->exists();
}

上述内容也会更有效,因为数据库正在完成更多的提升工作,而且您不必加载多个集合实例只是为了在事后对它们进行计数。

【讨论】:

  • 这会消除错误,但不会为已经提交评论的用户隐藏表单,它总是返回 false @Rwd
  • @user11710915 您是否希望它检查是否存在任何评论或是否存在多个评论?
  • 我想检查一下,如果用户已经提交了对该产品的评论(那么表单不应该显示),但如果没有,它应该显示表单。这应该适用于不同的用户@Rwd
  • 可以说,如果用户一已经在产品一中提交了评论,则不应为用户一显示表单,如果用户二尚未提交评论,则应显示表单@Rwd
  • @user11710915 我已经更新了我的答案。我从您的原始逻辑中假设用户可能对产品进行多次评论,因为您的代码中的逻辑表示超过 1 (&gt; 1)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
相关资源
最近更新 更多