调用未定义的方法 Illuminate\Database\Eloquent\Builder::transform(



我正在尝试在 Laravel 中进行查询,它应该根据日期、pick_score和按小时排序以及我数据集中的一些特定字符串值选择值。查询在下面,但我得到"调用未定义的方法 Illuminate\Database\Eloquent\Builder::transform((",我不确定我做错了什么。

$matches = Match::select()
->where('date', $date)
->where('pick_score', '<>', '0')
->orderBy('hour')
->transform(function ($match) {
if(
$match->competition_type == "ATP - SINGLES" 
or
$match->competition_type == "WTA - SINGLES"
){
$match->competition_type = -1;
}else{
$match->competition_type = 'competition_type';
}
return $match;
})
->sortBy('competition_type');

任何人都可以帮助我解决此错误吗?

共享方法名称可能会有点混乱,但它的要点是,在 Builder 对象上运行orderBy()只返回相同的 Builder 对象,而不是Collection。 若要获取所需的集合,请告诉生成器首先通过在orderBy()transform()之间放置get()调用来执行查询。

顺便说一句,Collection::transform()不返回任何东西。 我认为你想要的是map().

$matches = Match::select()
->where('date', $date)
->where('pick_score', '<>', '0')
->orderBy('hour')
->get()
->transform(function ($match) {
if(
$match->competition_type == "ATP - SINGLES" 
or
$match->competition_type == "WTA - SINGLES"
){
$match->competition_type = -1;
}else{
$match->competition_type = 'competition_type';
}
return $match;
})
->sortBy('competition_type');

它可以解决您的问题。

Laravel有雄辩的orm库用于数据库查询。 https://laravel.com/docs/6.0/eloquent。它具有从数据库获取数据作为集合的 get 方法。收集方法与雄辩相似。所以大多数时候人们会混淆它们。转换是一种集合方法。https://laravel.com/docs/6.x/collections#method-transform

最新更新