【发布时间】: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