I'm using Laravel v8
I have 3 models as:Family, FamilyMember, FamilyRelationship
Family table:
id
address
created_at
updated_at
1
test
NULL
NULL
Family Relationship table:
id
name
created_at
updated_at
1
Head
NULL
NULL
2
Spouse
NULL
NULL
3
Child
NULL
NULL
Family Member table:
id
first_name
last_name
family_id
family_relationship_id
1
John
Doe
1
1
2
Jane
Doe
1
2
3
Max
Doe
1
3
4
Mary
Doe
1
3
I have created relation in the Family model as
public function members(){
return $this->hasMany(FamilyMember::class, 'family_id');
}
And Family Relationship relation in Family Member model as
public function familyrelationship()
{
return $this->belongsTo(FamilyRelationship::class, 'family_relationship_id');
}
I'm using Datatable to display the Family Information along with Head of the family
I want to display columns id and address from Family model and first_name and last_name from Family Member model where the family member relationship is Head.
How should go ahead with making relationship to display only head of the family detail in the datatable grid which is searchable too?
Above thing can be easily achieved using eloquent JOINs but I want to know if this can be achieved using relationship functionality provided by Laravel.
you can try whereHas mixing with hasOne , to build a new relation:
public function members(){
return $this->hasMany(FamilyMember::class, 'family_id');
}
// then your new relation:
public function head(){
return $this->hasOne(FamilyMember::class, 'family_id')->whereHas('familyrelationship',function ($query){
$query->where('name','Head');
});
}
hasOne, will take only first result ...
Related
I am building a web app using Laravel (5.7). At some point, the user must input his location that is comprised of:
Country
State
City
So for this, I created 4 tables:
Countries table:
Columns: id, name
Relations: hasMany states
States table:
Columns: id, country_id, name
Relations: hasMany cities, belongsTo country
Cities table:
Columns: id, state_id , name
Relations: hasMany Locations, belongsTo state
Locations table:
Columns: id, city_id, name
Relations: belongsTo City
My questions are:
1) Is this the correct approach?
2) Obviously, there are countries out there without the "state" segmentation. If this is the case, how are we going to move up to the Country (using relationships) when the state is not present?
3) How do we know the minimum Eloquent relationships we can use on each model? Because a country also has a lot of cities. Do we use this relationship as well, or is it OK because states has a lot of cities?
I would be very happy if someone helped me clear this out. Its been bothering me for quite some time.
Thanks in advance.
There are three tables: users, profiles, friend_request
profiles table's column : profile_id, id (foreign key with users) , first_name,last_name
friend_request's table column : request_id, sender_id,to_user_id, request_status
logic : if profile_id exist in either sender_id column or to_user_id of friend_request table with request_status 2 then they are friends.
example : sender_id to_user_id request_status
5 6 2
$request_accept = DB::table('friend_request')->select('profiles.profile_id','profiles.first_name',
'friend_request.request_id')->leftjoin('profiles', function($join)
{
$join->on('friend_request.sender_id' , '=','profiles.profile_id');
$join->orOn('friend_request.to_user_id' , '=','profiles.profile_id');
}
)->where('to_user_id',$my_profile_id)->orwhere('sender_id',$my_profile_id)->where('interest_status','2')->whereNotIn('profiles.profile_id', function($q) use ($my_profile_id)
{
$q->select('profile_id')->from('profiles')->where('profile_id',$my_profile_id);
})->groupby('profiles.profile_id')->get();
wherenotin i snot working.
If I understand what you are asking...
Probably better to make these all models, with relationships, then you could do a much simpler query, for example like this.
Assume your friend_request table now has a FriendRequest model with a user relationship. The query below uses a $userId, assume this is the ID for the user whom you wish to get all the friend requests.
FriendRequest::where('to_user_id', $my_profile_id)->get();
If everything is set up correctly, the user will not be returned as they cannot send themselves a friend request.
I have 4 tables.
User table:
id col1 col2
CoursesAssigned table:
id user_id course_id approved
CourseInfo table:
id parent_id
CourseParents table:
id start_date end_date
I think the table names and its column names are self explanatory.
I have 2 kinds of users - i) assigned ii) unassigned. I show them in 2 different pages.
While showing the assigned students I need those students from users table for each of whom there is at least one row in CoursesAssigned table where user_id is his own user id and the approved field is 1 and the course_id in that row has its own parent_id (from CourseInfo) with end_date (from CourseParents) greater than or equal to today.
For showing unassigned students, I need those students from users table, for each of whom -
either
there is NO row in CoursesAssigned table where the user_id is his own user id and the approved column has a value 1. That is for an unassigned user, there may exist a row with his own user id but the approved field contains 0.
or
there may be rows in CoursesAssigned table with the user_id being his own user id and the approved field having a value 1 but the parent_id obtained from CourseInfo has from CourseParents an end_date which is less than today's date.
I can write a query for assigned students like:
$date=date('Y-m-d');
$records = User::join('CoursesAssigned','users.id','=','CoursesAssigned.user_id')
->join('CourseInfo','CourseInfo.id','=','CoursesAssigned.course_id')
->join('CourseParents','CourseParents.id','=',
'CourseInfo.parent_id')
->where('CoursesAssigned.approved','=',1)
->where('CourseParents.end_date','>=',$date)
->select('users.id','users.col1','users.col2')
->orderBy('users.id','desc');
But that should not produce the correct result as that does not check CoursesAssigned table for at least 1 row that meets all mentioned criteria. Q1) Or should it ?
Q2) What is about the query that fetches only the unassigned students ?
EDIT : The answer can be in ORM, query builder or even raw MySql for Laravel format.
EDIT2 : Let me clarify the scenario here :
I need to fetch both assigned and unassigned users separately.
To obtain assigned users I have 1 rule: How can I get those users who have at least 1 approved course in CoursesAssigned table and the parent (obtained from CourseInfo table )of that course has the end_date (in CourseParents table) greater than or equal to today.
To obtain unassigned students I have 2 rules :
Rule 1: Get those tudents who do not have any approved course (i.e. all courses have approved =0). They are unassigned students
Rule 2: Get those students who have approved courses but none of the approved courses meet the criteria of those for assigned students . That means there is no approved course there that has a parent whose end_date is greater than or equal to today.They are also unassigned students.
I'm still not completely sure about your table relationships but from my guess, I came up with the following solution, first create the relationships using Eloquent models:
User Model (for usres table):
namespace App;
use App\Course;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
public function courses()
{
return $this->hasMany(Course::class);
}
}
Course Model (for CoursesAssigned table):
namespace App;
use App\CourseInfo;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $table = 'CoursesAssigned';
public function courseInfo()
{
return $this->belongsTo(CourseInfo::class);
}
}
CourseInfo Model (for CourseInfo table):
namespace App;
use App\CourseParent;
use Illuminate\Database\Eloquent\Model;
class CourseInfo extends Model
{
protected $table = 'CourseInfo';
public function courseParent()
{
return $this->belongsTo(CourseParent::class, 'parent_id');
}
}
CourseParent Model (for CourseParents table):
namespace App;
use Illuminate\Database\Eloquent\Model;
class CourseParent extends Model
{
protected $table = 'CourseParents';
}
Get the assigned users:
$assignedUsers = User::whereHas('courses', function($query) {
$query->where('approved', 1)
->with(['courses.courseInfo.courseParent' => function($query) {
$query->where('end_date', >= \Carbon\Carbon::now());
}]);
})->get(); // paginate(...) for paginated result.
This should work if my assumption is correct. Try this for assignedUsers first then let me know and then I'll look into it for the other requirements. Also make sure that you do understand about Eloquent relationships between models and implement everything correctly (with correct namespace).
Note: This answer is incomplete and need further info because the answer is a result of direct conversation with OP over phone (OP called me because I was reachable) so some changes will be made overtime if needed and will be continued step by step until I can come up with a solution or leave it.
I have Book and Store models which have belongsToMany relationship.
In Book.php
public function stores(){
return $this->belongsToMany('App\Store')->withPivot('qty');
}
In Store.php
public function books(){
return $this->belongsToMany('App\Book')->withPivot('qty');
}
Now I just want to know the total number of books in store A and B together. How can I do it with eloquent ORM? I can get all books belonging to store A and B using whereHas but cannot go further to aggregate the qty field in the pivot table.
So you want the total qty of books by combination of store id and book id
The way you've described your DB structure, it looks like your pivot table has exactly these columns: book_id, store_id and qty
So all you really need to do is:
DB::table('book_stores')->get()
I am allowing users to add multiple subjects on the fly while adding a student, for example when you are adding a student you can add a subject i.e Math then you will set its attributes teacher name, credit hours etc. But when saving to db I need to save the information to my middle table students_subjects
id | student_id | subject_id | teacher_name | credit_hours
The problem is that how I can save the information for each subject. I can save the subject_id in a hidden field and get that but how would I know that this id is related to that particular subject and get the teacher and credit hours for that id.
how I can save the information for each subject
DB::table('students_subjects')->insert([
'student_id' => $input['studentId'],
'subject_id' => $input['subjectId'],
'teacher_name' => $input['teacherName'],
'credit_hours' => $input['creditHours'],
]);
I can save the subject_id in a hidden field and get that but how would I know that this id is related to that particular subject
If you have the subject_id - then you know what subject it relates to.
get the teacher and credit hours for that id
$result = DB::table('students_subjects')
->select(['teacher_name', 'credit_hours'])
->where('id', $id)
->first();
So you have 3 tables. And a many-many relationship
students
subjects
student_subject
Take a look at https://laravel.com/docs/5.2/eloquent-relationships#many-to-many to learn about defining your eloquent models.
From your question, I would consider changing how you structure your database.
A student hasMany subjects. A subject belongsTo teacher.
So I would have 4 tables as follows:
students
- id
- first_name
- last_name
student_subject
- student_id
- subject_id
- credit_hours (assuming this is the number of hours the student has studied?)
subjects
- id
- name
- credit_hours (assuming this is the total credit value)
teachers
- id
- name
- subject_id
If a teacher can teach many subjects, then you would need to add a subject_teacher pivot table.
When adding the student, if you could provide a dropdown list of subjects whose value is the subject_id, then when you select the subject - you post the subject_id back to php ready to insert into the DB.