首页 > 解决方案 > 无法加载模型与 Eloquent 的关系

问题描述

对于我正在处理的 Laravel 7.3 项目,我有两个如下所示的表(相关部分):

(“prestation” = 英文中的“性能”)

Schema::create('prestations', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->unsignedInteger('prestation_categories_id');
    ...
    $table->timestamps();
});
Schema::create('prestation_categories', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    ...
    $table->timestamps();
});

这就是我设置他们关系的方式:

Prestation.php

/**
 * @return BelongsTo
 */
public function categories ()
{
    return $this->BelongsTo('App\PrestationCategory');
}

PrestationCategory.php

/**
 * @return HasMany
 */
public function prestations ()
{
    return $this->hasMany('App\Prestation');
}

现在,我的 Laravel 被用作运行在其顶部的 SPA 的 API,并以 JSON 格式显示其数据。我有一个旨在显示所有数据的页面,以及性能类别的至少两个字段。我的目标是有一个如下所示的 JSON 字符串:

[
  {
    id: 1,
    title: 'Some title',
    description: 'Lorem ipsum sic amet...',
    category: { // or prestation_category, I don't care
      id: 2
      color: '#42B79CFF',
    },
    ...
  },
  {
    ...
  }
]

但是,我在加载这个相关类别时遇到了很多麻烦。我发现了无数关于这个主题的问题,但奇怪的是,没有任何帮助。

这是我尝试设置控制器操作的方法

public function dashboard ()
    {
  // Try #1
  $prestation = Prestation::with('categories:id,color')->get();

  // Try #2
  $prestations = Prestation::with(['categories' => function ($query) {
    $query->select('color', 'whole_day');
  }])->get();

  // Try #3
  $prestations = Prestation::join('prestation_categories', 'prestations.prestation_categories_id', '=', 'prestation_categories.id')->get();

  return response()->json($prestations);
}

这些方法中的每一个都返回我的“Prestation”,但是,相关的类别没有加载。

我在哪里做错了,我该如何解决?

先感谢您

标签: phplaraveleloquentrelationship

解决方案


默认情况下,迁移模式的 id() 字段是大整数。因此,要在相关表之间保持相同的约束,您将使用相同的字段类型。

// prestations
Schema::create('prestations', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->unsignedBigInteger('prestation_categories_id');// pay attention here
    ...
    $table->timestamps();
});

// prestation_categories
Schema::create('prestation_categories', function (Blueprint $table) {
    $table->id();// this field is unsigned big integer
    $table->string('title');
    ...
    $table->timestamps();
});

旁注:虽然 PHP 允许在函数/方法名称中不区分大小写,但它是belongsTo()方法。尝试坚持此处描述的命名约定和最佳实践,您将跳过许多非受迫性错误。


推荐阅读