Laravel Query不返回任何数据

时间:2016-03-18 12:55:00

标签: php sqlite laravel laravel-5 eloquent

我有一个数据库表'里程碑'其中包含3列:

start_location 
end_location
miles

我的查询是使用我的前程模型中的范围选择器构建的(start_location和end_location正在适当地传递):

//Get miles for the start_location -> end_location

public function scopeMileageDistance($query)
{
    return $query->where('start_location', '=', 'start_location')->where('end_location', '=', 'end_location');
}

//THIS ONE WORKS
//Get a list of the locations from the DB
public function scopeMileageLocations($query)
{
    return $query->select('start_location')->groupBy('start_location');
}

我在我的控制器中访问它的方式与访问我的位置查询(工作方式)相同:

//WORKS
$locations = Mileage::MileageLocations()->get();
//DOES NOT WORK
$distance = Mileage::MileageDistance()->get();

当我饺子时:

dd($distance);

显示为什么都没有返回。但是如果我在数据库上运行这个SQL查询 - 它会返回相应的对象:

select * from mileages where start_location = 'pointA' and end_location = 'pointB'

我正在通过Ajax调用访问它,当用户进行下拉选择时会触发该调用:

        $.ajax({
            url: 'created',
            type: 'POST',
            data: {_token: CSRF_TOKEN, start_location:start_location.value, end_location:end_location.value},
            dataType: 'JSON',
            success: function (data) {
            console.log(data);
                $("#result").append(JSON.stringify(data));
                return data;
            }
        });

只是想知道我是否对我的范围选择器和/或查询做错了。

5 个答案:

答案 0 :(得分:1)

是的,因为您需要将一些参数传递给您的函数:

public function scopeMileageDistance($query, $start, $end)
{
    $query->where('start_location', '=', $start)->where('end_location', '=', $end)->get();
}

所以,你可以用这样的东西来使用它:

$start = $request->get($start_location);
$end = $request->get($end_location);
...
        ->scopeMileageDistance($start, $end);
...

我希望它有所帮助。

答案 1 :(得分:0)

您需要返回构建器

public function scopeMileageDistance($query)
{
    return $query->where('start_location', '=','start_location')
    ->where('end_location', '=', 'end_location');
}

答案 2 :(得分:0)

尝试从您的示波器中删除get()并添加return

public function scopeMileageDistance($query)
{
    return $query->whereStartLocation('start_location')->whereEndLocation('end_location');
}

问题是你没有从范围返回任何东西,这就是你得到空结果的原因。

答案 3 :(得分:0)

您是否在查询中添加了where参数:

我正在谈论关键点A& pointB

您需要返回查询

return $query->where('start_location', '=', 'pointA')->where('end_location', '=', 'pointB')->get();

答案 4 :(得分:0)

试试这个:

public function scopeMileageDistance($query)
{
    return $query->whereStartLocation('start_location')->whereEndLocation('end_location');
}
相关问题