php - 无法加载模型与 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”,但是,相关的类别没有加载。
我在哪里做错了,我该如何解决?
先感谢您
解决方案
默认情况下,迁移模式的 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()方法。尝试坚持此处描述的命名约定和最佳实践,您将跳过许多非受迫性错误。
推荐阅读
- python - Google API Cloud 身份组().create():customer_id 字段是什么?
- sql - SQL - 如何连接两个表,但只有某些东西是完全匹配的?
- object-detection - GluonCV 对象检测微调 - 选择修改哪些层(冻结其余层)
- javascript - 从数组生成带状索引块
- android - 在 Android 设备上运行 Ionic5 应用程序时出现 net::ERR_INVALID_RESPONSE 错误
- charts - 从我的 chartjs 饼图中更改一个数据集的旋转
- javascript - Uncaught TypeError: $(...).select2 is not a function--Slect2 not working
- python - Python curses box() 由 6s 和 0s 组成
- powershell - Powershell 证书颁发者错误
- r - 我安装了“光栅”包,但无法在 R 中加载它的库。这里有什么问题,我们如何解决这个问题?