【发布时间】:2018-03-03 07:51:14
【问题描述】:
我遵循了这个教程:toptal
我想为以下类型的音箱应用创建一个 API:
/ api / v1 / Apps -> list of apps
/ api / v1 / Apps / 1 /category -> list of category of app 1
/ api / v1 / Apps / 1/category/1/sounds -> list of components of category 1 of app 1
你有教程吗? 或者如何调整我的路线文件?我有 3 个控制器吗?
------------- 编辑 ------------
我创建了模型和控制器:
class App extends Model{
protected $fillable = ['title'];
}
class Category extends Model{
protected $fillable = ['name'];
}
控制器:
<?php
namespace App\Http\Controllers;
use App\App;
use Illuminate\Http\Request;
class AppController extends Controller{
public function index(){
return App::all();
}
public function show($id){
return App::find($id);
}
}
<?php
namespace App\Http\Controllers;
use App\Category;
use App\App;
use Illuminate\Http\Request;
class CategoryController extends Controller{
public function index(App $app){
return App::find($app);
}
public function show(App $app, Category $category){
//
}
}
我创建了迁移文件:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAppsTable extends Migration{
public function up(){
Schema::create('apps', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration{
public function up(){
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('app_id')->unsigned();
$table->timestamps();
});
Schema::table('categories', function($table) {
$table->foreign('app_id')->references('id')->on('apps');
});
}
}
还有我的 routes/api.php 文件:
Route::group(['prefix' => 'v1'], function() {
Route::resource('App', 'AppController', ['only' => ['index', 'show']]);
Route::resource('app.category', 'CategoryController', ['only' =>['index', 'show']]);
});
所以我调用了网址:/api/v1/App
结果:[{"id":1,"title":"Movies","created_at":null,"updated_at":null},{"id":2,"title":"football"," created_at":null,"updated_at":null}]
但是当我调用 url:/api/v1/App/2/category 时我不明白这是如何工作的
在 CategoryController 中。
【问题讨论】:
-
也许使用以下路线结构会更直观:
/api/v1/categories-> 类别列表,/api/v1/categories/1/products- 类别 1 的产品列表,/api/v1/categories/1/products/1/components-> 列表第 1 类产品 1 的组件。