Laravel 5.2中的错误Eloquent - 无法转换为String

时间:2016-01-20 17:18:30

标签: php laravel laravel-5 laravel-5.1

我是Laravel的新手,我正在阅读这些教程并坚持不懈。

我有一个复杂的查询,我需要重复使用where子句中的一个参数更改。我在我的模型中将其添加为查询范围,然后从相应的Controller中调用它。当我尝试返回数据时,我收到此错误:

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

以下是查询范围:

public function scopeCrosstab($wellID)
{
    return static::select('sampleDate', \DB::raw("
                max(if(chemID=1, pfcLevel, ' ')) as 'PFOA', max(if(chemID=1, noteAbr, ' ')) as 'PFOANote'
            "))
        ->leftJoin('SampleNote', 'WellSample.noteID', '=', 'SampleNote.noteID')
        ->where('wellID', '=', $wellID)
        ->groupBy('sampleDate');
}

这是控制器代码:

public function smith() 
{
    $wellSamples = WellSample::crosstab(2);

    return $wellSamples->get();

    //return view('pages.wellsample', compact('wellSamples'));
}

我已经尝试了许多不同的代码排列,带引号,双引号等。如果我在查询范围内对代码值进行硬编码,那么它就可以了,但我需要能够使其动态化。

1 个答案:

答案 0 :(得分:2)

范围方法至少需要一个参数,第一个参数必须是$query。然后构建传递给scope方法的查询变量。像这样:

public function scopeCrosstab($query, $wellID)
{
    return $query->select('sampleDate', \DB::raw("
                max(if(chemID=1, pfcLevel, ' ')) as 'PFOA', max(if(chemID=1, noteAbr, ' ')) as 'PFOANote'
            "))
        ->leftJoin('SampleNote', 'WellSample.noteID', '=', 'SampleNote.noteID')
        ->where('wellID', '=', $wellID)
        ->groupBy('sampleDate');
}