Laravel eloquent: переименование имен столбцов с использованием «colllection» в запросе с несколькими взаимосвязями - PullRequest
0 голосов
/ 27 мая 2018

Сценарий:

Мне нужно получить данные из таблицы свойств, которые связаны с городом, районом и категорией, и передать весь результат через коллекцию, которая "украсит" уродливые столбцы, чтобыхорошие имена.

Так что я делаю выбор, используя метод WITH:

//Query example
$result = Property::query();
$result = $result()->select('somefields')
->with('city')
->with('neighborhood')
->with('category')
->paginate($limit);

//Lets get results and use collection to rename ugly columns name:
PropertyResource::collection($result);

// Он будет переименовывать поля на основе этого решения: https://laravel.com/docs/5.6/collections#method-toarray

Мой вопрос: PropertyResource переименовывает только столбцы, извлеченные из таблицы «Свойство».Таблицы «город», «категория» и «окрестности» сохраняют имя собственных столбцов.

Как передать $ result через другие коллекции?

1 Ответ

0 голосов
/ 27 мая 2018

В методе сбора я могу переименовать весь результат следующим образом:

 <?php

    namespace App\Http\Resources\v1;

    use Illuminate\Http\Resources\Json\Resource;

    class Property extends Resource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'id'                    => $this->SOMEFIELD,
                'featured'              => $this->SOMEFIELD,
                'superFeatured'         => $this->SOMEFIELD,
//THIS ONE COMES FROM A RELATIONSHIP
                'description'           => $this->propertyAdvertisement->SOMEFIELD,
                'saleValue'             => $this->SOMEFIELD,
                'saleFormOfPayment'     => $this->SOMEFIELD,
                'vacationRentValue'     => $this->SOMEFIELD,
                'annualRentValue'       => $this->SOMEFIELD,
                'dormitories'           => $this->SOMEFIELD,
                'suites'                => $this->SOMEFIELD,
                'wc'                    => $this->SOMEFIELD,
                'parkingSpaces'         => $this->SOMEFIELD,
                'coverImage'            => $this->SOMEFIELD,
                'coverDescription'      => $this->SOMEFIELD,
                'coverOrder'            => $this->SOMEFIELD,
                'features'              => $this->SOMEFIELD,
                'category'              => $this->SOMEFIELD,
                'subcategory'           => $this->SOMEFIELD,
                'city'                  => $this->SOMEFIELD,
                'condominium'           => $this->SOMEFIELD,
                'neighborhood'          => $this->SOMEFIELD,
                'ref'                   => $this->SOMEFIELD,
                'privateArea'           => $this->SOMEFIELD,
                'totalArea'             => $this->SOMEFIELD,
                'terrainSize'           => $this->SOMEFIELD,
                'finances'              => $this->SOMEFIELD,
                'ownerParcels'          => $this->SOMEFIELD
            ];
        }
    }

Таким образом, только одна коллекция может переименовать весь результат.

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