gpt4 book ai didi

php - 将参数传递给模型中的函数

转载 作者:行者123 更新时间:2023-11-29 11:43:12 24 4
gpt4 key购买 nike

我的 Controller 中有以下方法。

public function show($semester_name = null)
{
$semester = $this->getSemester($semester_name);

$matches = Match::GetMatches($semester->id);

$semesters = Semester::where('active', 1)->orderBy('name')->get();

return view('entities/match.indexMatched', compact('matches', 'semesters'));
}

我的模型中的这个方法:

public function scopeGetMatches($id)
{
$query = "SELECT

some code...

WHERE matches.semester_id = " . $id . "
ORDER BY 2, 3, 5, 6
";

return DB::select(DB::raw($query));
}

但是我收到错误类 Illuminate\Database\Eloquent\Builder 的对象无法转换为字符串

我确信我得到了有效的 $semester->id。

帮助某人?

最佳答案

任何范围方法都接受 Illuminate\Database\Eloquent\Builder 的第一个参数实例,所以你的方法应该看起来 像:

public function scopeGetMatches(\Illuminate\Database\Eloquent\Builder $builder, $id)

基本上范围方法应该修改当前模型查询的状态,因为范围方法与该模型的查询构建器的当前实例相互传递 - 例如:

Posts::where('published', true)->newest()->get()

public function scopeNewest($builder) {
$builder->orderBy('created_at', 'DESC');
}

等同于:

Posts::where('published', true)->orderBy('created_at', 'DESC')->get()

所以你的实现是错误的,可能只是一个静态方法。

您可以在 Laravel 文档上找到更多信息:https://laravel.com/docs/5.2/eloquent#query-scopes .

关于php - 将参数传递给模型中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35415161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com