繁体   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