【问题标题】:Unable to load a model's relationship with Eloquent无法加载模型与 Eloquent 的关系
【发布时间】:2020-04-10 21:06:06
【问题描述】:

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

("prestation" = "performance" in English)

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”,但是,相关的类别没有加载。

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

提前谢谢你

【问题讨论】:

  • 如果你将scheme设置为$table->unsignedBigInteger('prestation_categories_id');有什么变化吗?
  • ... 它奏效了。我保留了第三次尝试的代码,现在我发现自己的字段来自“Prestation”和“PrestationCategory”!欢迎发表您的回复,我会接受的

标签: php laravel eloquent relationship


【解决方案1】:

默认迁移模式的 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() 方法。尝试坚持使用here 描述的命名约定和最佳实践,您将跳过很多非强制错误。

【讨论】:

  • 我刚刚重命名了我的模型/迁移/关系,现在它可以正常工作了。男孩,我花了几个小时寻找愚蠢的表名。再次感谢!
  • 我们从不停止学习。 ;) 只要你坚持命名 Laravel 的官方文档,并且大部分(至少最常用)都在 GitHub 链接中进行了描述,你会看到生产力的巨大提升。
猜你喜欢
  • 2018-05-26
  • 2014-11-22
  • 2021-07-04
  • 2017-01-12
  • 2020-04-13
  • 2015-12-27
  • 2020-10-26
  • 2019-09-20
  • 2015-10-29
相关资源
最近更新 更多