如何使用雄辩的方式返回基于数据库关系的json响应 [英] how to return a json response based on database relationship using eloquent

查看:86
本文介绍了如何使用雄辩的方式返回基于数据库关系的json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Laravel很新。我正在找出与雄辩的工作。



我有两个表:类别和产品。这两张桌子有一对多关系。 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}
]
}
]

模型:



Category.php

 <?php 

class类别扩展Eloquent {

protected $ table ='categories';

public function products(){
return $ this-> hasMany('Product');
}
}

Product.php

 <?php 

class产品扩展Eloquent {

protected $ table ='products';

public function categories(){
return $ this-> belongsTo('Category');
}
}

数据库表: / p>

create_categories_table:

 <?php 

使用Illuminate\Database\Schema\Blueprint;
使用Illuminate\Database\Migrations\Migration;

class CreateCategoriesTable extends Migration {

public function up()
{
Schema :: create('categories',function(Blueprint $ table) {
$ table-> increment('id');
$ table-> string('name') - > unique();
$ table-> timestamps );
});
}

...
}

create_products_table:

 <?php 

use Illuminate\Database\Schema\Blueprint;
使用Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration {

public function up()
{
Schema :: create('products',function(Blueprint $ table) {
$ table-> increment('id');
$ table-> string('name') - > unique();
$ table-> string 'price');
$ table-> unsignedInteger('category_id');
$ table-> foreign('category_id') - > references('id') - > on 'categories');
$ table-> timestamps();
});
}

...
}

控制器



class ApiController extends BaseController {

  public function getIndex(){

$ categories = Category :: all();

return Response :: json(array('data'=> $ categories));
}

}



我知道如何返回所有类别或产品,或只返回类别的名称,但我似乎找不到上面提到的json响应示例的解决方案。



如果有人知道这将是非常有帮助的。谢谢提前。

解决方案

如果我正确理解你的问题,你可以这样做:

  public function getIndex(){
$ categories = Category :: with('Products') - > get();
return Response :: json(array('data'=> $ categories));
}

with()渴望加载关系,所以你几乎得到了你想要的。



顺便说一句,你可能想改变这个方法的名称

  public function categories(){
return $ this-> belongsTo('Category');
}

category()因为每个产品只能属于一个类别。


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.

解决方案

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.

这篇关于如何使用雄辩的方式返回基于数据库关系的json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆