【问题标题】:How to fetch data from DB tables to json format? LARAVEL 5.8如何从数据库表中获取数据到 json 格式?拉拉维尔 5.8
【发布时间】:2021-12-22 11:03:08
【问题描述】:

我是一名业余前端开发人员,正在为我的大学从事网络开发项目。我将独自完成这个项目,已经完成了网站的前端部分。我使用了一个临时 API 来获取在我的视图中传递的数据。现在,由于我必须使用数据库,所以我构建了数据库并尝试将数据获取到我的控制器。这对我来说太复杂了,到目前为止进展几乎为零。迈出小步我现在正试图将包含特定行的所有表键和值的 JSON 数据提取到我的控制器上的一个变量中。响应包含受保护的数据,我不知道如何以正确的方式获取它们。

任何提示或建议将不胜感激。

我的测试服务器的控制器

<?php

namespace App\Http\Controllers;
use App\circuits;
use App\constructor_results;
use App\constructors;
use App\driver_standings;
use App\drivers;
use App\lap_times;
use App\pit_stops;
use App\qualifying;
use App\races;
use App\results;
use App\seasons;
use App\status;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {

        $data = DB::table('circuits')
        ->select('circuits.*')
        ->where(['circuitId' => '6'])
        ->get();

        print_r(response()->json($data));       

    }
 
}

响应 (想要的值显示在行尾)

Illuminate\Http\JsonResponse Object ( [data:protected] => [{"circuitId":"6","circuitRef":"monaco","name":"Circuit de Monaco","location":"Monte-Carlo","country":"Monaco","lat":"43.7347","lng":"7.42056","alt":"7","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_de_Monaco"}] [callback:protected] => [encodingOptions:protected] => 0 [headers] => Symfony\Component\HttpFoundation\ResponseHeaderBag Object ( [computedCacheControl:protected] => Array ( [no-cache] => 1 [private] => 1 ) [cookies:protected] => Array ( ) [headerNames:protected] => Array ( [cache-control] => Cache-Control [date] => Date [content-type] => Content-Type ) [headers:protected] => Array ( [cache-control] => Array ( [0] => no-cache, private ) [date] => Array ( [0] => Tue, 09 Nov 2021 18:09:00 GMT ) [content-type] => Array ( [0] => application/json ) ) [cacheControl:protected] => Array ( ) ) [content:protected] => [{"circuitId":"6","circuitRef":"monaco","name":"Circuit de Monaco","location":"Monte-Carlo","country":"Monaco","lat":"43.7347","lng":"7.42056","alt":"7","url":"http:\/\/en.wikipedia.org\/wiki\/Circuit_de_Monaco"}] [version:protected] => 1.0 [statusCode:protected] => 200 [statusText:protected] => OK [charset:protected] => [original] => Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [circuitId] => 6 [circuitRef] => monaco [name] => Circuit de Monaco [location] => Monte-Carlo [country] => Monaco [lat] => 43.7347 [lng] => 7.42056 [alt] => 7 [url] => http://en.wikipedia.org/wiki/Circuit_de_Monaco ) ) ) [exception] => )

【问题讨论】:

标签: json laravel database controller fetch


【解决方案1】:

看看https://laravel.com/docs/8.x/eloquent-resources

(应该对5.8也有效https://laravel.com/docs/5.8/eloquent-resources,思路一样)

当然,您可以随时将 Eloquent 模型或集合转换为 JSON 使用他们的 toJson 方法;然而,雄辩的资源提供 对您的 JSON 序列化进行更精细和健壮的控制 模型及其关系。

所以你可以添加一个新的 Circuit Eloquent 模型,在那里描述所有字段等,并添加 toJson 方法,该方法将返回数组(在那里你可以映射你想要从模型返回的内容)。

我更喜欢使用 API 资源,因为在该功能中,您可能需要在不同的地方做出不同的响应。

<?php
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class CircuitResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        //add all fields which you want to return from the Circuit model
        return [
            'id' => $this->id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

然后在控制器中,你会像这样使用它

use App\Http\Resources\CircuitResource;
use App\Models\Circuit;

...

return response()->json(new CircuitResource(Circuit::find(6)));

模型将是

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Circuit extends Model
{
    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'circuitId';
}

要查找 1 个项目,最好使用 find() 方法。但是如果你搜索多个,你会收到一个 Collection 对象。在这种情况下,您将需要在创建的资源类上使用适当的方法,并且从操作中,您应该返回

return response()->json(new CircuitResource::collection(Circuit::all()));

【讨论】:

  • 回复“Oleksandr H.”我创建了资源。我在资源中传递了正确的字段,然后运行以下行:“return response()->json(new CircuitResource(Circuit::find(6)));”我收到一个错误:“SQLSTATE [HY000]”显然它默认搜索列 circuit.id 并且它不存在
  • @GkChris99 要修复它,您需要在 Circuit Eloquent 类中告诉您主键的名称(默认为 id),请参阅 laravel.com/docs/8.x/eloquent#primary-keys
  • @GkChris99 我已经更新了我的答案,希望更清楚如何使用它。
猜你喜欢
  • 1970-01-01
  • 2019-02-21
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2020-12-18
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多