我对Laravel很新 . 我正在考虑与Eloquent合作 .
假设我有2个表:类别和产品 . 这两个表有一对多的关系 . 1类可以有很多产品 .
我想返回一个JSON响应,该响应由一系列类别组成,其中每个类别都有一系列产品 . 它应该如下所示:
[
{"name":"Category 1", "products": [
{"name":"Product 1","price":"2.50"},
{"name":"Product 2","price":"2.50"}
]
},
{"name":"Category 2", "products": [
{"name":"Product 1","price":"1.95"},
{"name":"Product 2","price":"2.15"}
]
}
]
Models:
Category.php
<?php
class Category extends Eloquent{
protected $table = 'categories';
public function products(){
return $this->hasMany('Product');
}
}
Product.php
<?php
class Product extends Eloquent {
protected $table = 'products';
public function categories(){
return $this->belongsTo('Category');
}
}
Database tables:
create_categories_table:
<?php
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')->unique();
$table->timestamps();
});
}
...
}
create_products_table:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration {
public function up()
{
Schema::create('products', function(Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('price');
$table->unsignedInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}
...
}
Controller:
class ApiController扩展BaseController {
public function getIndex(){
$categories = Category::all();
return Response::json(array('data' => $categories));
}
}
我知道如何返回所有类别或产品或只返回类别的名称,但我似乎无法找到上面提到的json响应示例的解决方案 .
如果有人知道这将是非常有帮助的 . 提前致谢 .
1 回答
如果我理解你的问题,你可以简单地这样做:
with()
渴望加载关系,这样你就能得到你想要的东西 .顺便说一下,您可能想要更改此方法的名称
改为
category()
,因为每个产品只能属于一个类别 .