首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将数据从DB表中提取为json格式?LARAVEL 5.8

如何将数据从DB表中提取为json格式?LARAVEL 5.8
EN

Stack Overflow用户
提问于 2021-11-09 18:26:33
回答 1查看 598关注 0票数 0

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

如有任何建议或建议,将不胜感激。

我的测试服务器的控制器

代码语言:javascript
复制
<?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));       

    }
 
}

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

代码语言:javascript
复制
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] => )
EN

回答 1

Stack Overflow用户

发布于 2021-11-09 18:50:13

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

(它应该适用于5.8以及https://laravel.com/docs/5.8/eloquent-resources,其想法是一样的)

当然,您可以使用

方法将有说服力的模型或集合转换为JSON;但是,雄辩的资源为您的模型及其关系的JSON序列化提供了更细粒度和更健壮的控制。

因此,您可以添加一个新的电路雄辩模型,描述所有字段等等,并添加toJson方法,它将返回数组(在那里,您可以映射您希望从模型返回的内容)。

我更喜欢使用API参考资料,因为在特性中,您可能需要不同地方的不同响应。

代码语言:javascript
复制
<?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,
        ];
    }
}

然后在控制器中,您将使用它就像

代码语言:javascript
复制
use App\Http\Resources\CircuitResource;
use App\Models\Circuit;

...

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

模型将是

代码语言:javascript
复制
<?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对象。在这种情况下,您将需要在创建的资源类上使用适当的方法,并且应该从操作中返回

代码语言:javascript
复制
return response()->json(new CircuitResource::collection(Circuit::all()));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69903251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档