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.
Related
I have two tables contact_us and upload_new_car.
contact_us table contains columns:
id
name
email
phone
message
created_at
updated_at
upload_new_car contains columns:
id
name
phone_number
car_name
car_price
location
car_model_year
car_model
variant
driven
fuel
transmission
city
no_of_owners
upload_1
upload_2
upload_3
upload_4
upload_5
created_at
updated_at
How can I get the UNION of these tables in Laravel? Please help
Not allowing to different size of columns is not laravel's businuess. It is a matter of SQL .You can follow [this link] for more info about UNION statements .
On the other hand for laravel you can use those syntax using union (We can benefit from selecting the same count of columns from each tables).
$first = DB::table('contact_us')
->select('name','phone');
$users = DB::table('users')
->select('name','phone_number as phone')
->union($first)
->get();
dd($users)
I have such entities as:
Company
Person
Company hasMany Persons. So in the persons table there is company_id column.
I return company list, which I pass to CompanyResource. There I return has_persons => $this->persons()->exists() value.
Then I checked the result of DB::getQueryLog() and I found out that there is only one SQL query, which does not have count or anything like that.
In order to count how many persons a company has, Laravel should make one query per company, shouldn't it? Like select count (*) from persons where company_id = 5 for example
try this
$this->persons->count()
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.