【发布时间】:2023-03-09 20:10:01
【问题描述】:
我是 Laravel 学习者。我现在想学的是从后端发送一个JSON文件到前端,这样我就可以用这个JSON文件来画图了。
在我的模型中,我编写了一个函数来提取值和时间戳created_at。这是一段代码,它将返回与单个网站关联的谷歌页面速度值和时间戳。然后我想使用JS 绘制图表,其中垂直值是谷歌页面速度,水平是时间戳created at。
谁能帮帮我?是否需要将返回值改为数组?
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Notification;
use App\Status;
class ChartController extends Controller
{
public function speedHistory(){
$o_status = Status::where('name','speed')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get();
if($o_response){
return response()->json($o_response);
}
// return an empty json array instead of false
//return false;
return response()->json(array());
}
}
路线是
Route::get('json','ChartController@speedHistory');
一直抱怨方法未定义。这是我的模型 las 通知扩展模型 { protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
public function statuses(){
return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
}
【问题讨论】:
-
L4
return Response::json($data_array, $status_code);或 L5return response()->json($data_array, $status_code); -
您能解释一下
$o_response->values部分吗?如果我没记错的话 $o_reponse 应该是一个数组,你不能在数组上调用对象属性。尝试将 $o_reponse 查询从->get()更改为->first() -
@devk : $o_response->values ,没错,它是一个数组。一个网站可能有不同的谷歌页面速度,例如 70,80,100 等,它作为值存储在数据透视表中,我将其提取为 $o_response->values。
标签: javascript php json laravel