HOW TO
In the Student Controller, how to sort the results by student name?
How to sort the results by student's guardian name?
TABLE STRUCTURE
taxonomies
id
entity_type - It contains the class name of the owning model.
entity_id - It contains the ID value of the student.
students
id
name
guardians
id
student_id
name
CONTROLLER
StudentController.php
public function getStudents()
{
return Taxonomy::with([
'entity',
'entity.guardian'
])
->where('entity_type', 'Student')
->get();
}
MODEL
Taxonomy.php
public function entity()
{
return $this->morphTo();
}
Student.php
public function taxonomies()
{
return $this->morphMany('App\Taxonomy', 'entity');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
Guardian.php
public function student()
{
return $this->belongsTo('App\Student');
}
Use sortBy():
$taxonomies = Taxonomy::with('entity.guardian')
->where('entity_type', 'Student')
->get();
// Solution #1: Sort results by student name.
$sortedTaxonomies = $taxonomies->sortBy('entity.name');
return $sortedTaxonomies->values();
// Solution #2: Sort results by student's guardian name.
$sortedTaxonomies = $taxonomies->sortBy('entity.guardian.name');
return $sortedTaxonomies->values();
Related
In Skill model
public function employee_skill()
{
return $this->belongsToMany(Employees::class, 'employee_skills', 'skill_id', 'employee_id');
}
In Employee model
public function skills()
{
return $this->belongsToMany(Skill::class, 'employee_skills', 'employee_id', 'skill_id');
}
I have a EmployeeSkill model and in employee_skills table columns are
id, employee_id, skill_id
I use this for skills based employee count
{{ $skill->employee_skill->count() }}
But i want to return only active employee.
You can add a where clause to your employee_skill relationship:
public function employee_skill()
{
return $this->belongsToMany(Employees::class, 'employee_skills', 'skill_id', 'employee_id')
->where('status', 'Active');
}
or if you want to leave it open:
$skill->employee_skill->where('status', 'Active')->count()
I want to recieve all users from a group.
The problem is in this group their are student users (with a pivot table) and normal users.
So i have to merge them together, but i still want to maintain all possibilities from eloquent.
I came to this:
dd($this->belongsToMany(User::class)->union($this->hasManyThrough(User::class,Student::class,'class_id','id','id','user_id'))->get());
But as result i get:
My database relationships
Users
- id
Group
- id
Students
- id
- user_id (fk to users)
- class_id (fk to groups)
User_Group
- user_id (fk to users)
- group_id (fk to groups)
User-model:
public function students()
{
return $this->hasMany(Student::class);
}
public function groups()
{
return $this->belongsToMany(Group::class);
}
Student-model
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function class()
{
return $this->belongsTo(Group::class, 'class_id');
}
Group-model
public function students()
{
return $this->hasMany(Student::class, 'class_id');
}
public function users()
{
return $this->belongsToMany(User::class);
}
public function members()
{
//this causes the problem!!
return $this->belongsToMany(User::class)->union($this->hasManyThrough(User::class,Student::class,'class_id','id','id','user_id'));
}
in User model relationship
public function group(){
return $this->belongsToMany(Group::class);
}
in Group model relationship
public function user(){
return $this->belongsToMany(User::class, 'user_group');
}
in Students model relationship
public function user(){
return $this->belongsToMany(User::class, 'user_id', 'id');
}
public function group(){
return $this->belongsToMany(Group::class, 'class_id', 'id');
}
you can call now
$users = User::whereHas('groups',function ($query){
$query->where('group_id',1);
})->get();
Sometimes you have two relations from one model to another, due pivot tables. In my example you could go from users to groups with the relation user_groups and the relation students. To get all users that belong to a certain group i need to call both relations. To solve this issue, i made use of Abdulmajeed's example to solve it. You can see the code below. Thanks for helping me out.
public function members()
{
return User::whereHas('groups', function($q)
{
$q->where('id',$this->id);
})->orWhereHas('students', function($q)
{
$q->where('class_id',$this->id);
});
}
In my project I want show name in category and province table and this table i relation with it in user table.
This is my code.
In controller:
$user=user::with('province','category')->where([['id',$id]])->first();
In model:
//relation with province model (invert relation)
public function province()
{
return $this->belongsTo('App\Model\province');
}
//relation with province model (invert relation)
public function category()
{
return $this->belongsTo('App\Model\category');
}
But in return just id is returned not name and other property.
In output show this:
category_id: 3
province_id: 6
Wrong $user=user::with('province','category')->where([['id',$id]])->first();
//Use
$user=user::with(['province','category'])->where('id', $id)->first();
Put the foreign key and local key to relatioships.
public function province()
{
return $this->belongsTo('App\Model\province','foreign_key','local_key'); // put your FK and LK here
}
public function category()
{
return $this->belongsTo('App\Model\category','foreign_key','local_key'); // put your FK and LK here
}
You can get the result by
$user=user::where('id','=',$id)->first();
if(isset($user))
{
if(isset($user->province))
{
//do whatever you want
}
if(isset($user->category))
{
//do whatever you want
}
}
I am using Laravel 5.6. I am trying to query information from the grading_info table but I also want to return the students name and other info from the student_info table. I only want to return records in the grading_info table that are related to the currently logged in teacher. Currently its returning information for all teachers. I know I can add a where clause but I am trying to learn eloquent and was wondering if there was any way to accomplish this?
Teachers and students can have many enteries in the grading_info table and any teacher can grade any student.
I would like to return something like this
{
gradeID,
gradeDate,
gradeInfo
.....
student: {
studentName,
studentPhoneNumber,
studentEmail
......
}
}
users table (only stores teachers, not student)
id
teacher_info
teacherID (linked to id from users table)
student_info
id (auto increment. not relation to the users table)
grading_info
studentID (linked to id from student_info)
teacherID (linked to id from users)
User model
public function grades(){
return $this->hasMany(GradingInfo::class, 'studentID');
}
GradingInfo model
public function teacher(){
return $this->belongsTo(User::class, 'id', 'teacherID');
}
public function student() {
return $this->belongsTo(StudentInfo::class, 'studentID', 'id');
}
StudentInfo model
public function grades() {
return $this->hasMany(SessionInfo::class, 'studentID', 'id');
}
TeacherInfo model
// Nothing in here.
TeacherController
public function getGrades(Request $request)
{
$user = Auth::user(); // This is the teacher
$grades = $user->with('sessions.student')->orderBy('created_at', 'DESC')->get();
return response()->json(['sessions' => $sessions], 200);
}
You have Many to Many relationship between user(teacher) and student(student_info) tables
User Model
public function gradeStudents(){
return $this->belongsToMany(StudentInfo::class, 'grading_info', 'teacherID', 'studentID');
}
public function info(){ //get teacher info
return $this->hasOne(TeacherInfo::class, 'teacherID');
}
StudentInfo model
public function gradeTeachers(){
return $this->belongsToMany(User::class, 'grading_info', 'studentID', 'teacherID');
}
Now Fetch the data (TeacherController)
public function getGrades(Request $request)
{
$user = Auth::user(); // This is the teacher
$students = $user->gradeStudents; // it will return all graded students by logged in teacher
return response()->json(['students' => $students], 200);
}
Here grading_info is a pivot table for Many-To-Many relationship
for details check this https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
Fetch Extra info from pivot table
If you want to add extra info in pivot table (grading_info) then add column (info) in this table and then need to change relationship like this
public function gradeStudents(){
return $this->belongsToMany(StudentInfo::class, 'grading_info', 'teacherID', 'studentID')
->withPivot('info')
->as('grade')
->withTimestamps();
}
Now if you fetch data
$user = Auth::user(); // This is the teacher
$students = $user->gradeStudents;
foreach($students as $student){
print_r($student);
print_r($student->grade->info);
print_r($student->grade->created_at);
}
I'm having some trouble when trying to fetch records from database. Here's the table schema:
users
--------------
id
username
password
email
divisions
--------------
id
name
employee
--------------
name
birth_date
status
class
division_id
user_id
projects
--------------
id
title
body
user_id
So, for the relationship explanations:
relationship
Okay, i'm trying to fetch project based on division_id on table employee with the following code:
# query code
$division_id = 10;
$items = Project::with(['user.employee.division' => function($query) use ($division_id) {
$query->where('id', $division_id);
}])->get();
I've added the required belongsTo, hasMany or hasOne to the models.
# User.php
class User extends Authenticatable
{
public function employee()
{
return $this->hasOne('App\Employee', 'user_id');
}
public function projects()
{
return $this->hasMany('App\Project', 'user_id');
}
}
# Division.php
class Division extends Model
{
public function employee()
{
return $this->hasMany('App\Employee', 'division_id');
}
}
# Employee
class Employee extends Model
{
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
public function division()
{
return $this->belongsTo('App\Division', 'division_id');
}
}
# Project.php
class Project extends Model
{
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
}
So, what's the problem?
Here's the thing, when i run the query code i'm getting all the records and the division object on employe relationship returning null.
If anyone thinks my code is wrong, please enlighten me.
Thanks.
So after some digging, i found an answer. The query code should change to whereHas:
# query code
$division_id = 10;
$items = App\Project::whereHas('user.employee.division',
function($query) use ($division_id) {
$query->where('divisions.id', $division_id);
})
->with(['user.employee.division']) // N+1 problem
->get();
reference: Laravel 5.3 Constraining Eager Loads not working