问题
I'm quite new to Laravel. I'm figuring out to work with Eloquent.
Let's say I have 2 tables: categories and products. These two table have a one-to-many relationship. 1 category can have many products.
I would like to return a JSON response which consists of an array of categories where each category has an array of products. It should look like this:
[
{"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 extends BaseController {
public function getIndex(){
$categories = Category::all();
return Response::json(array('data' => $categories));
}
}
I know how to return all of the categories or products or only the name of a category but I cannot seem to find the solution for the example of json response I mentioned above.
If anyone knows this it would be really helpful. Thanks in advance.
回答1:
If I understood your question correctly, you could simply do this:
public function getIndex(){
$categories = Category::with('Products')->get();
return Response::json(array('data' => $categories));
}
The with()
eager loads the relationship so you get pretty much what you want.
By the way, you'll probably want to change the name of this method
public function categories(){
return $this->belongsTo('Category');
}
to category()
instead, since every product can only belong to one category.
来源:https://stackoverflow.com/questions/24600013/how-to-return-a-json-response-based-on-database-relationship-using-eloquent