如何根据Laravel用户表中的主题代码显示主题表中的主题名称 [英] How to show subjects name from subjects table depending on subjects codes in users table in laravel

查看:47
本文介绍了如何根据Laravel用户表中的主题代码显示主题表中的主题名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名称为subj_one,subj_two,subj_three等的字段中有带有科目代码的学生表.还有另一张名为科目的表,其中包含科目代码和名称.

I have students table with subject codes in the fields named like subj_one, subj_two, subj_three etc. There are another table named subjects with subject's codes and name.

ID  Name    Subj_one   Subj_two   Subj_three
1   Mohan     101         102       107
2   Sohan     245         101       147
3   Neha      101         103       247

主题表中的样本记录

subj_code            subj_name
  101                Hindi
  102                English
  103                Physics
  147                Chemistry
  245                Math

现在我在显示学生表中的学生数据时如何显示主题名称?

Now how to show subject name while I am showing student's data from students table?

推荐答案

在这种情况下,首先,为每个列创建关系.(不过不建议这样做,但是,因为您提到要在不更改数据库的情况下实现此目的)

In this case, firstly, create relation for each column. (not recommended though, but, since you mentioned that you want to achieve this without changing the database)

例如,用于Student :: class(模型)中的 Subj_one

e.g for Subj_one, in the Student::class (model)

public function subjectOne() {
    return this->belongsTo('App\Subject', 'Subj_one', 'subj_code'); // 'foreign_key', 'other_key'
}

然后,当您查询学生时,请使用 with().

Then, when you are querying for the students, use with().

$students = Student::with('subjectOne', 'subjectTwo')->get();

刀片式服务器最新

@foreach($students as $student)
    {{ $student->Name }} with {{ $student->subjectOne->subj_name }}
@endforeach

请仔细阅读雄辩的关系文档.

这篇关于如何根据Laravel用户表中的主题代码显示主题表中的主题名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆