[英]I get The Error Call to a member function addEagerConstraints() on integer
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。
急切加载(with)只能用于关系: https://laravel.com/docs/6.x/eloquent-relationships#eager-loading
所以getAverageRatingAttribute
不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.