【问题标题】:how to return a json response based on database relationship using eloquent如何使用 eloquent 根据数据库关系返回 json 响应
【发布时间】:2014-08-27 07:27:54
【问题描述】:

我对 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"}
                                     ]
   }
]

型号:

Category.php

<?php

class Category extends Eloquent{

    protected $table = 'categories';

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

产品.php

<?php

class Product extends Eloquent {

    protected $table = 'products';

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

数据库表:

创建类别表:

<?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();
        });
    }

    ...
}

创建产品表:

<?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();
        });
    }

    ...
}

控制器:

类 ApiController 扩展 BaseController {

public function getIndex(){

    $categories = Category::all();

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

}

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

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

【问题讨论】:

    标签: json laravel eloquent one-to-many foreign-key-relationship


    【解决方案1】:

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

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

    with() 渴望加载关系,因此您几乎可以得到您想要的。

    顺便说一句,您可能想要更改此方法的名称

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

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

    【讨论】:

    • 非常感谢您的快速回复。这就是我要感谢的。小问题:有没有办法在类别和产品对象的响应中不返回 id、created_at 和 updated_at 字段?当然不改变数据库结构。
    • 您可以添加select('field1', 'field2')-&gt;get() 来选择任意数量的字段,但我不确定它如何与with() 一起使用。您可能需要编写select('categories.field1') 等,并明确写出每个字段。或者也许它根本不起作用,但我认为它应该。
    • @Sven 在模型上使用$hidden$visible 属性来隐藏toArray/toJson 方法中的这些字段。
    • 谢谢大家,感谢您的帮助:),我会给你 +1,但我不能,因为我是 stackoverflow 的新手:p
    猜你喜欢
    • 2023-03-20
    • 2021-03-29
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2015-11-14
    • 2021-03-21
    • 2022-10-09
    • 2017-03-25
    相关资源
    最近更新 更多