Вложенный ответ JSON в Laravel 5.7 - PullRequest
0 голосов
/ 19 мая 2019

Я новичок в laravel и создаю ответ json для трех таблиц. Я пробую до двух таблиц, но я не могу добавить третью таблицу в кодировку. Пожалуйста, добавьте некоторую кодировку в мою функцию. Таблица

  1. category_type = {category_type_id, имя_категории};
  2. main_category = {main_category_id, category_type_id, main_category_name}
  3. sub_category = {sub_category_id, category_type_id, main_category_id, sub_category_name}

Я вкладываю json во вторую таблицу, теперь хочу присоединиться к третьей таблице.

функция, которую я создал:

public function fetchCategory()
{
    $tableIds = DB::select( DB::raw("SELECT * FROM table_category_type"));

    $jsonResult = array();

    for($i = 0;$i < count($tableIds);$i++)
    {
        $jsonResult[$i]["category_id"] = $tableIds[$i]->category_id;
        $jsonResult[$i]["category_type"] = $tableIds[$i]->category_type;
        $id = $tableIds[$i]->category_id;
        $jsonResult[$i]["main_category"] = DB::select( DB::raw("SELECT *  FROM table_main_category WHERE category_type_id = $id"));

    }

    return Response::json(array(
                'success'     =>  '1',
                'data'    =>  $jsonResult),
                200
        );
}

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

    {
        "success": "1",
        "data": [
            {
                "category_id": 1,
                "category_type": "Study",
                "main_category": []
            },
            {
                "category_id": 2,
                "category_type": "Sports",
                "main_category": [
                    {
                        "main_category_id": 1,
                        "category_type_id": 2,
                        "category_name": "Popular Sports"
                    },
                    {
                        "main_category_id": 2,
                        "category_type_id": 2,
                        "category_name": "Team Sports"
                    },
                    {
                        "main_category_id": 3,
                        "category_type_id": 2,
                        "category_name": "Racquet Sports"
                    },
                    {
                        "main_category_id": 4,
                        "category_type_id": 2,
                        "category_name": "Fitness"
                    },
                    {
                        "main_category_id": 5,
                        "category_type_id": 2,
                        "category_name": "Recreation"
                    }
                ]
            },
            {
                "category_id": 3,
                "category_type": "Other",
                "main_category": []
            }
        ]
    }

Я вложил main_category в category_type сейчас, я хочу, чтобы вложенная sub_category в main_category plz нуждалась в изменениях в кодировании. Я вложил три таблицы в отношение один ко многим и много ко многим. Поскольку я новичок в Laravel, я не могу понять, как отправить идентификатор во вложенном отношении

1 Ответ

1 голос
/ 19 мая 2019

Поскольку вы новичок в Laravel, вы можете не знать, что такое Eloquent. И если я правильно понимаю ваш вопрос, у нас есть 3 таблицы, и нам нужно связать их через отношения, чтобы мы могли получить каждый элемент реляционного объекта с данными.

Итак, у нас есть 3 таблицы:

  1. category_types
  2. main_categories
  3. sub_categories

Примечание: допускается, что названия таблиц во множественном числе, а названия моделей в единственном числе. Например: category_types для таблицы и CategoryType для класса модели.

Хорошо, прежде всего, вам нужно создать миграции:

php artisan make:migration create_category_types_table

public function up()
{
    Schema::create('category_types', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name', 255)->nullable();
        $table->timestamps();
    });
}

php artisan make:migration create_main_categories_table

public function up()
{
    Schema::create('main_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('category_type_id')->index();
        $table->string('name', 255)->nullable();
        $table->timestamps();
    });
}



php artisan make:migration create_sub_categories_table

public function up()
{
   Schema::create('sub_categories', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->bigInteger('category_type_id')->index();
       $table->bigInteger('main_category_id')->index();
       $table->string('name', 255)->nullable();
       $table->timestamps();
   });
}

Итак, в функции этой миграции у нас есть автоинкремент и имя

Обратите внимание, что вы можете написать только имя в этой таблице, а не category_name и category_type_id как Вы всегда знаете, что этот атрибут относится к таблице партуклара

Хорошо, теперь мы можем создавать и настраивать наши модели. Для модели CategoryTypes мы должны создайте 2 отношения для main_categories и sub_categories, например:

php artisan make:model CategoryType
php artisan make:model MainCategory
php artisan make:model SubCategory

И это код модели нашей категории:

class CategoryType extends Model {
    protected $fillable = ['name'];

    protected $dates = [
        'created_at',
        'updated_at'
    ];

    public function mainCategories()
    {
        return $this->hasMany(MainCategory::class);
    }

    public function subCategories() {
       return $this->hasMany(SubCategory::class);
    }
}

Поскольку мы определяем наши реализации модели CategoryType, мы можем теперь получать данные, которые нам нужны в нашем контроллере:

public function fetchCategory()
{
    $categories = CategoryType::with(['mainCategories', 'subCategories'])->get();

    return response()->json($categories, 200);
}

И наш JSON:

[
{
    "id": 1,
    "name": "Books",
    "created_at": "2019-05-19 13:24:51",
    "updated_at": "2019-05-19 13:24:51",
    "main_categories": [
        {
            "id": 1,
            "category_type_id": 1,
            "name": "Si-Fi",
            "created_at": "2019-05-19 13:26:07",
            "updated_at": "2019-05-19 13:26:08"
        },
        {
            "id": 2,
            "category_type_id": 1,
            "name": "Biography ",
            "created_at": "2019-05-19 13:26:33",
            "updated_at": "2019-05-19 13:26:34"
        },
        {
            "id": 3,
            "category_type_id": 1,
            "name": "Tall tale ",
            "created_at": "2019-05-19 13:26:57",
            "updated_at": "2019-05-19 13:26:58"
        },
        {
            "id": 4,
            "category_type_id": 1,
            "name": "Short story",
            "created_at": "2019-05-19 13:27:07",
            "updated_at": "2019-05-19 13:27:07"
        },
        {
            "id": 5,
            "category_type_id": 1,
            "name": "Fantasy",
            "created_at": "2019-05-19 13:27:17",
            "updated_at": "2019-05-19 13:27:18"
        }
    ],
    "sub_categories": [
        {
            "id": 1,
            "category_type_id": 1,
            "main_category_id": 1,
            "name": "Space exploration",
            "created_at": "2019-05-19 13:42:35",
            "updated_at": "2019-05-19 13:42:35"
        },
        {
            "id": 2,
            "category_type_id": 1,
            "main_category_id": 2,
            "name": "Historical biography",
            "created_at": "2019-05-19 13:42:36",
            "updated_at": "2019-05-19 13:42:36"
        },
        {
            "id": 3,
            "category_type_id": 1,
            "main_category_id": 5,
            "name": "The Lord of the Rings",
            "created_at": "2019-05-19 13:42:37",
            "updated_at": "2019-05-19 13:42:37"
        }
    ]
},
{
    "id": 2,
    "name": "Sports",
    "created_at": "2019-05-19 13:24:57",
    "updated_at": "2019-05-19 13:24:57",
    "main_categories": [
        {
            "id": 6,
            "category_type_id": 2,
            "name": "Popular Sports",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 7,
            "category_type_id": 2,
            "name": "Team Sports",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 8,
            "category_type_id": 2,
            "name": "Racquet Sports",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 9,
            "category_type_id": 2,
            "name": "Fitness",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 10,
            "category_type_id": 2,
            "name": "Recreation",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        }
    ],
    "sub_categories": [
        {
            "id": 4,
            "category_type_id": 2,
            "main_category_id": 6,
            "name": "Football",
            "created_at": "2019-05-19 13:42:37",
            "updated_at": "2019-05-19 13:42:37"
        },
        {
            "id": 5,
            "category_type_id": 2,
            "main_category_id": 6,
            "name": "Basketball",
            "created_at": "2019-05-19 13:42:37",
            "updated_at": "2019-05-19 13:42:37"
        }
    ]
},
{
    "id": 3,
    "name": "Study",
    "created_at": "2019-05-19 13:25:24",
    "updated_at": "2019-05-19 13:25:25",
    "main_categories": [
        {
            "id": 11,
            "category_type_id": 3,
            "name": "Web Development",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 12,
            "category_type_id": 3,
            "name": "Sofware Development",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 13,
            "category_type_id": 3,
            "name": "Mangement",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 14,
            "category_type_id": 3,
            "name": "Tourism",
            "created_at": "2019-05-19 13:27:35",
            "updated_at": "2019-05-19 13:27:36"
        },
        {
            "id": 16,
            "category_type_id": 3,
            "name": "Geography",
            "created_at": "2019-05-19 13:33:36",
            "updated_at": "2019-05-19 13:33:37"
        }
    ],
    "sub_categories": [
        {
            "id": 6,
            "category_type_id": 3,
            "main_category_id": 11,
            "name": "PHP",
            "created_at": "2019-05-19 13:42:29",
            "updated_at": "2019-05-19 13:42:30"
        },
        {
            "id": 7,
            "category_type_id": 3,
            "main_category_id": 11,
            "name": "Ruby",
            "created_at": "2019-05-19 13:42:31",
            "updated_at": "2019-05-19 13:42:32"
        },
        {
            "id": 8,
            "category_type_id": 3,
            "main_category_id": 11,
            "name": "Java",
            "created_at": "2019-05-19 13:42:33",
            "updated_at": "2019-05-19 13:42:33"
        }
    ]
}

]

Надеюсь, это поможет вам. И, пожалуйста, прочитайте Laravel Docs для получения дополнительной информации

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