Relationships using Eloquent

霸气de小男生 提交于 2020-01-15 11:13:48

问题


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

  • Student studies in a class for a particular year
  • Each class for that year will have 10 results (1 result for each month in an year)
  • Each result will contain the state for a test in a month (pass or fail)

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

回答1:


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

Result.php model

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

Class.php model

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

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

Student.php model

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

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 model

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

Class.php model

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');

EDIT: Your tables are using a custom identifier, so you must implement protected $primaryKey = 'custom_id'; on each model.



来源:https://stackoverflow.com/questions/38144246/relationships-using-eloquent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!