有没有办法使此代码看起来更漂亮,将这两种方法合并为仅一种?
/**
* With authenticated user's rating
*
* @param Builder $query
* @return Builder
*/
public function scopeWithAuthUserRating(Builder $query): Builder
{
return $query
->when(auth()->check(), static function (Builder $query) {
return $query->with('authUserRating');
});
}
public function authUserRating(): MorphMany
{
return $this->morphMany(Rating::class, 'rateable')->where('user_id', auth()->id());
}
The authUserRating()
method only exists because I need to define that relation for the scope method that needs it right above.
In other words, is there an elegant way to refactor these 2 methods into just 1? I am looking for something like this :
/**
* With authenticated user's rating
*
* @param Builder $query
* @return Builder
*/
public function scopeWithAuthUserRating(Builder $query): Builder
{
return $query
->when(auth()->check(), static function (Builder $query) {
return $query
->with(
$wtf_am_i_doing->morphMany(Rating::class, 'rateable')->where('user_id', auth()->id())
)
->as('authUserRating');
});
}