簡體   English   中英

我在 integer 上收到對成員 function addEagerConstraints() 的錯誤調用

[英]I get The Error Call to a member function addEagerConstraints() on integer

  1. 這是一個正常的代碼
  2. 拖拉機台 class
  3. UserReviews以下代碼。

     public function getReviewAvgAndCount() { return $this->hasMany(UserReview::class, 'tractor_id'); } function getAverageRatingAttribute() { return ($this->getReviewAvgAndCount()->count()); }

    公共function拖拉機表(){

     return $this ->belongsTo('App\Model\TractorTable','tractor_id');

    }

致電 Controller:

$obj=TractorTable::with('tractorImage','tractorSpecData','getAverageRatingAttribute','drive')->orderBy('tractor_id', 'desc')->take(5)->get();

你不能“急切地加載”不是關系的東西。 getAverageRatingAttribute是訪問器,而不是關系方法; 它不返回關系類型 object [BelongsTo、HasMany 等]。

由於您並不急切地加載訪問者將要訪問的關系,因此您可能只是試圖獲取關系的計數。 Eloquent 能夠專門執行此操作,而無需完全加載關系並且不必計算返回的記錄。 為此目的有一個withCount方法:

TractorTable::with('tractorImage', 'tractorSpecData', 'drive')
    ->withCount('getReviewAvgAndCount') // the relationship
    ->orderBy('tractor_id', 'desc')
    ->take(5)
    ->get();

然后您應該能夠通過每個TractorTable實例上的屬性訪問該計數(關系名稱蛇大小寫 + '_count'):

$tractor->get_review_avg_and_count_count;

假設您使用的是 Laravel >= 5.2。

Laravel 6.x 文檔 - Eloquent - 關系 - 計數相關模型withCount

急切加載(with)只能用於關系: https://laravel.com/docs/6.x/eloquent-relationships#eager-loading

所以getAverageRatingAttribute不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM