使用口才的关系 [英] Relationships using Eloquent

查看:78
本文介绍了使用口才的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel 5中使用了Eloquent,在表之间的关系上有些困惑.这些是软件的现有表,不能更改.

I'm using Eloquent in Laravel 5 and am a bit confused in relations between tables. These are existing tables of a software and cannot be altered.

我有下表显示学生的历史详细资料.所有表都创建了模型类.

I have the following tables that shows historical details of a student. All tables have model classes created.

student
-------
student_id (PK)
first_name
last_name

class
-----
class_id (PK)
name
section
year    //2012, 2013 etc
student_id (FK)

result
------
result_id (PK)
class_id (FK)
month       // jan, feb etc
status      //pass or fail

下面是每个表格的详细信息

Below are the details of each table

  • 某年级的学生学习
  • 该年度的每个课程将有10个结果(一年中每个月有1个结果)
  • 每个结果将包含一个月内测试的状态(通过或失败)

我想根据以下示例访问对象.您可以指导在模型类中建立关系吗?

I want to access objects based on the below examples. Can you guide on setting up relations in the model classes

student->class(2013)->result(jan)
result(feb)->class(2016)->student

推荐答案

首先,您应该定义模型之间的关系:

First of all you should define the relationships between your models:

Result.php模型

public function class(){
    return $this->belongsTo('Class::class');
}

Class.php模型

public function results(){
    return $this->hasMany('Result::class');
}

public function student(){
    return $this->belongsTo('Student::class');
}

Student.php模型

public function classes(){
    return $this->hasMany('Class::class');
}

然后,您可以使用一些查询.对于第一个示例student->class(2013)->result(jan):

Then, you can use some queries. For your first example student->class(2013)->result(jan):

$results = Student::find($student_id)->classes()->where('year', '2013')->results()->where('month', 'jan')->get();

此外,如果您需要多次按年搜索类,并按月搜索结果,则可以轻松地在模型中添加如下所示的方法:

Also, if you will need to search classes by year and results by month a lot of times, you can easily add some methods like this in your models:

Student.php模型

public function classesByYear($year){
    return $this->classes()->where('year', $year)->get();
}

Class.php模型

public function resultsByMonth($month){
    return $this->results()->where('month', $month)->get();
}

因此上一个示例将变为:

So the previous example will become:

$results = Student::find($student_id)->classesByYear('2013')->resultsByMonth('jan');


您的表正在使用自定义标识符,因此您必须在每个模型上实现protected $primaryKey = 'custom_id';.

这篇关于使用口才的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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