lundi 29 juillet 2019

Laravel Eloquent Repository - Query giving unexpected result?

I'm using laravel eloquent queries to get the result of all students belonging to a department. The relationship is like this: Each department has classes. Each class has students.

If we are writing this on MySQL, we can have two versions: Let's say we want students belonging to department 5.

  1. select * from class inner join student on class.id = student.class_id where class.department_id = 5;

Equivalent Laravel Eloquent Query:

return $classRepo->where(['department_id'=>5])
            ->select(['id','department_id'])
            ->with(['students'])
            ->get();

  1. select * from student inner join class on class.id = student.class_id where class.department_id = 5;

Equivalent Laravel Eloquent Query:

return $studentRepo
        ->with(['class' => function($query){
            $query->select(['id', 'department_id'])
                ->where(['department_id' => 5]);
        }])
        ->get();

Unexpectedly, the result from the first version is this:

[
    {
        "id": 3,
        "department_id" : 5,
        "students": [
            {
                "id": 61060,
                "name" : "Mark"
            },
            {
                "id": 61061,
                "name" : "Tony"
            }
           ]
    }
]

and from second version is this:

[
    {
        "id": 61057,
        "name" : "Smith",
        "class": null
    },
    {
        "id": 61058,
        "name" : "Jason",
        "class": null
    },
    {
        "id": 61060,
        "name" : "Mark",
        "class": {
            "id": 3,
            "department_id": 5
        }
    },
    {
        "id": 61061,
        "name" : "Tony",
        "class": {
            "id": 3,
            "department_id": 5
        }
    }
]

Can anyone explain me the difference in the results between the two versions? Why I am having nulls in the second version against the class key? How laravel eloquent is actually processing the queries?

classRepo is an object of 'Classes' class

class Classes extends Model{

    public function students()
    {
        return $this->hasMany('App\repoModels\Student','class_id','id');
    }

}


studentRepo is an object of 'Student' class

class Student extends Model{

   public function class()
    {
        return $this->hasOne('App\repoModels\Classes', 'id', 'class_id');
    }

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire