Laravel根据外键和id从不同的表中获取登录用户的数据

问题描述 投票:-1回答:1

嗨iam初学者laravel,我有四个表用户,学生,班级,部分

用户

  • ID
  • 用户名
  • 密码
  • 用户类型

学生们

  • ID
  • 那么
  • 滚动号
  • 班级号
  • SECTION_ID

  • ID
  • 班级名称

部分

  • ID
  • SECTION_NAME

当我通过使用以下方法登录获取用户名并从学生表中获取角色no时

user.php的

public function getAttribute($ key)

{$profile = student::where('stud_adm_id', '=', $this->attributes['username'])->first()->toArray();

    foreach ($profile as $attr => $value) {
        if (!array_key_exists($attr, $this->attributes)) {
            $this->attributes[$attr] = $value;
        }
    }

    return parent::getAttribute($key);
}

但我想从相关表中获取类名和节名也显示登录用户完整的配置文件....

并在视图页面中调用值,如下所示

<h4>ID: &nbsp;&nbsp;{{ Auth::user()->roll_no}}</h4>
<h4>Name: &nbsp;&nbsp;{{ Auth::user()->name }}</h4>

让我知道如何获得课程和部分的价值。

laravel-5.4
1个回答
0
投票

你可以使用Eloquent: Relationships

在student.php中定义关系

class Student {

    ...

    public function class() {
        $this->belongsTo('App\Class');
    }

    public function section() {
        $this->belongsTo('App\Section');
    }

    ...

}

然后你可以在获得class模型时检索sectionstudent关系。

$student = Student::where('stud_adm_id', $username)->first();
$class = $studnet->class;
$section = $student->section;
© www.soinside.com 2019 - 2024. All rights reserved.