【问题标题】:Responses JSON with Relationship - Laravel/Eloquent响应 JSON 与关系 - Laravel/Eloquent
【发布时间】:2018-09-05 23:03:57
【问题描述】:

我正在开发一个 Laravel 项目,我想为网站创建一个 REST API。在我的系统上,我有两个表:

博客和类别。表 blogs 有 category_id 列,这是一个引用 category 表中列 ID 的键。

博客迁移

class CreateBlogsTable extends Migration
{
    public function up()
    {
     Schema::create('blogs', function (Blueprint $table) {
     $table->increments('id');
     $table->string('title');
     $table->longtext('body');
     $table->string('category_id');
     $table->timestamps();
    });
   }
   .....
}

类别迁移

class CreateCategoriesTable extends Migration
{
    public function up()
    {
     Schema::create('categories', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->timestamps();
    });
   }
   ....
}

我的博客模型

class Blog extends Model
{
    protected $fillable = ['title', 'body', 'category_id'];
    public function category() {
       return $this->hasMany('app\Category');
    }
}

我的博客模型

class Category extends Model
{
    protected $fillable = ['name'];
    public function blog() {
       return $this->hasMany('app\Blog');
    }
}

所以,我创建了一个 BlogController 并配置了访问相应 API 函数的路由。

api/blogs/via GET是给我的控制器的index函数,函数长这样:

public function index()
{
    $blog = Blog::all();
    return response()->json($blog, 200);
}

有了这个,我可以从 blogs 表中获取数据

[
    {
        "id": 1,
        "title": "title from my blog",
        "text": "text body here",
        "category_id": "2",
        "created_at": "2018-09-05 21:08:21",
        "updated_at": "2018-09-05 21:08:21"
    }
]

但我想合并博客和类别表,并得到类似的回应

[
    {
        "id": 1,
        "title": "title from my blog",
        "text": "text body here",
        "category_id": "2",
        "created_at": "2018-09-05 21:08:21",
        "updated_at": "2018-09-05 21:08:21"
        "category": [{
           "id": 2,
           "name": "Development"
        }]
    }
]

有人帮忙吗?

【问题讨论】:

  • category 必须是 BelongsTo 关系。

标签: laravel rest api laravel-5 laravel-5.6


【解决方案1】:

您正在使用 hasMany 关系,而类别表中的博客没有参考 id,因此数据并未急切加载。如果您将迁移更改为

 class CreateCategoriesTable extends Migration
  {
     public function up()
     {
       Schema::create('categories', function (Blueprint $table) {
         $table->increments('id');
         $table->string('name');
         $table->timestamps();
         $table->integer('category_id');
      });
    }
   ....
  }

然后你可以使用

Blog::with('category')->get();

或者把关系改成

public function category(){
 return $this->belongsTo(Category::class);
}

并使用

Blog::with('category')->get();

【讨论】:

    【解决方案2】:

    加载关系,它将包含在序列化响应中。

    $blog = Blog::with('category')->get();
    

    这个例子是急切加载类别关系。

    我建议您阅读雄辩的关系文档:https://laravel.com/docs/5.6/eloquent-relationships

    【讨论】:

    • 我已经尝试过了,但我收到此错误:“在模式 [App\Blog] 上调用未定义的关系 [类别]。”
    • 我已经更新了我的答案,阅读我的笔记,你的关系被命名为类别。
    • 我已经重命名了这两个类别,但我收到此错误“找不到类'app\Category'。”还有什么问题
    • 你的命名空间是app 还是App
    • 我为 App 修复了我的命名空间应用程序,这几乎是 la ... 如果我让 $ category = Category :: with ('blogs') -> get ();我得到了我的类别列表,并且在每个类别中我都有该特定类别的博客,但这并不是我想要的。正如我在问题中提到的,我想查阅我的博客列表,并从每个博客中获取每个类别的名称。目前,如果我使用 $ blog = with ('categories') -> get () 我会得到博客列表,但使用 "categories": null
    【解决方案3】:

    我得到了解决方案,我只需要说博客属于一个类别,一个类别可以有几个博客

    class Blog extends Model
    {
        protected $fillable = ['title', 'body', 'category_id',];
        public function category()
        {
            return $this->belongsTo('App\Category');
        }
    }
    

    类别模型

    class Category extends Model
    {
        protected $fillable = ['name'];
        public function blogs() {
            return $this->hasMany('App\Blog');
        }
    }
    

    所以要列出具有类别详细信息的博客

    public function index()
    {
        $blogs = Blog::with('category')->get();
        return response()->json($blogs, 200);
    }
    

    所以要列出你的博客的类别

    public function index()
    {
        $categories = Category::with('blogs')->get();
        return response()->json($categories, 200);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 2021-03-23
      • 1970-01-01
      • 2016-11-21
      • 2019-02-09
      • 2014-02-01
      • 2021-07-04
      • 2020-12-23
      • 1970-01-01
      相关资源
      最近更新 更多