Как я могу работать с массивами и объектами json в рамках laravel? - PullRequest
0 голосов
/ 18 октября 2019

Я импортировал файл SQL в свою базу данных и перенес его таким образом ...

    public function up()
    {
        Schema::create('pokemon', function (Blueprint $table) {
            $table->string('id');
            $table->string('name');
            $table->json('types');
            $table->string('height');
            $table->string('weight');
            $table->json('abilities');
            $table->json('eggGroups');
            $table->json('stats');
            $table->string('genus');
            $table->string('description');
            $table->boolean('captured');
        });
    }

У меня возникла проблема с использованием таблиц "Способности" и "Статистика", поскольку они былиимпортируется как массив и объект. Я хотел бы иметь возможность использовать массивы и объекты из этих таблиц в моем интерфейсе. Как я могу правильно обслуживать их через мой API. Прямо сейчас все, что я получаю, это строки, которые выглядят как массивы / объекты.

Ресурс Pokemon

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Pokemon extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'types' => $this->types,
            'height' => $this->height,
            'weight' => $this->weight,
            'abilities' => $this->abilities,
            'eggGroups' => $this->eggGroups,
            'stats' => $this->stats,
            'genus' => $this->genus,
            'description' => $this->description,
            'captured' => $this->captured,
        ];
    }
};

Контроллер Pokemon

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Models\Pokemon;
use App\Http\Resources\Pokemon as PokemonResource;

class PokemonController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $searched_pokemon = Pokemon::where('name', 'LIKE', ("%" . $request->input('name') . "%"))->paginate(12);
        return PokemonResource::collection($searched_pokemon);
    }
}

Изображениезаписей базы данных sql

1 Ответ

2 голосов
/ 18 октября 2019

Я думаю, вам следует использовать приведение атрибутов в laravel Массив и JSON .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...