laravel - Laravel Eloquent 中两个表的连接结果错误?
问题描述
我目前正在尝试在多个表之间建立关系。
教育机构
id institution_name country city
1 ABC College UK London
用户教育
id user_id institution_id grade year
1 1 1 3.2 2010
关系是
class UserEducation extends Model {
public function educationInstitution()
{
return $this->hasMany(EducationInstitution::class,'institution_id');
}
}
class EducationInstitution extends Model{
public function userEducation()
{
return $this->hasMany(UserEducation::class);
}
}
最后在控制器中:
class UserEducationController extends Controller
{
public function getUserEducation()
{
$userEducation = UserEducation::with('education_institutions')
->where('user_id',auth()->user()->id)
->orderBy('created_at', 'desc')
->get();
return response()->json([
'userEducation' => $userEducation
]);
}
}
它给出以下错误:
调用模型 [App\Models\UserEducation] 上的未定义关系 [education_institutions]。
我期待着这样的回应:
{
"userEducation": [
{
"id": 1,
"user_id": 1,
"institution_id": 1,
"grade": "3.49",
"institution_name": "ABC College"
"country":"UK",
"city":"London"
}
}
如何解决?
解决方案
好吧,正如@Eahiya 所说,我的关系中有一点错误。此外,我更正::with('educationInstitution')
了@Sumit 的建议。
我目前的代码是:
class UserEducation extends Model {
public function educationInstitution()
{
return $this->belogsTo(EducationInstitution::class,'institution_id');
}
}
class EducationInstitution extends Model{
public function userEducation()
{
return $this->hasMany(UserEducation::class);
}
}
和控制器:
public function getUserEducation()
{
$userEducation = UserEducation::with('educationInstitution')
->where('user_id',auth()->user()->id)
->orderBy('created_at', 'desc')
->get();
return response()->json([
'userEducation' => $userEducation
]);
}
它现在工作正常。
推荐阅读
- ios - iOS - 独立于时区的本地通知
- python-2.7 - Pycharm 在控制台中运行代码时不显示局部变量
- azure - 我在使用 Azure 集成工具处理 XSLT 中的特定 EDI 856 HL 级别时遇到问题
- php - 使用 ffmpeg 将 mp4 转换为 x264 时数据无效,但将 flv 转换为 x264 时很好
- curl - 如何在 curl 中使用原始 YAML 文件来创建 Pod
- angular6 - 找不到管道“xxx”(
- visual-studio - 在 Visual Studio 2017 cmake 项目中指定命令行参数
- javascript - findOneAndUpdate mongodb 推送到现有数组
- python - 如何在 matplotlib 中包含另一个图形?
- listview - ListView 项目内的按钮 - 如何获取内容?