Inner Join laravel 5.2 - php

Fellow Coders,
I'm trying to use an inner join query to get multiple data from my relative tables.. What i'm trying to do is to get the (project_id as company_name - subproject_id as subproject_title). I tried to use the query as I will state below. Also I will post printscreens of my tables.
$values = DB::table('hour_registrations')->join('projects', 'id', '=', 'id')->join('subprojects','id', '=', 'id')->select('projects.*', 'id', 'subprojects.id')->get();
I would love some help with my question as I do not understand what to do now..

I think this should do the trick (if I understood your table structure correctly).
I would encourage you to read the official Laravel documentation on Joins.
$query = DB::table('projects')
->join('subprojects', 'projects.id', '=', 'subprojects.project_id')
->join('companies', 'projects.company_id', '=', 'companies.id')
->select('companies.company_name', 'projects.id', 'subprojects.id', 'subprojects.title')
->get();

Related

laravel query problem using join, what is missing?

first of all Im not good at english and im new using laravel framework. Im developing some school site for thesis purposes. And I think this might be a chance for me to learn laravel since many developers recommends laravel.
back to my problem hehe
This query runs right.
$questions = DB::table('questions')
->select('questions.id','questions.role','questions.postBody', 'questions.classCode', 'questions.postedById', 'questions.created_at', 'classroom.classroomName','classroom.icon','users.picture', 'students.firstName', 'students.middleName', 'students.lastName', 'students.suffix','students.studentNumber')
->join('classroom', 'classroom.classCode', '=', 'questions.classCode')
->join('users', 'users.id', '=', 'questions.postedById')
->join('students', 'students.email' , '=', 'users.email')
->orderBy('questions.created_at', 'DESC')
->skip($request->page - 5)
->take($request->page)
->get();
and when I adding other table ("teacher") i got no returns. This is the example of my query trying to join 'teacher' table and in here, im trying to select email of teacher
$questions = DB::table('questions')
->select('questions.id','questions.role','questions.postBody', 'questions.classCode', 'questions.postedById', 'questions.created_at', 'classroom.classroomName','classroom.icon','users.picture', 'students.firstName', 'students.middleName', 'students.lastName', 'students.suffix','students.studentNumber','teacher.email')
->join('classroom', 'classroom.classCode', '=', 'questions.classCode')
->join('users', 'users.id', '=', 'questions.postedById')
->join('students', 'students.email' , '=', 'users.email')
->join('teacher', 'teacher.email' , '=', 'users.email')
->orderBy('questions.created_at', 'DESC')
->skip($request->page - 5)
->take($request->page)
->get();
sorry for my bad english.
Can anyone help me? Thank you very much!
The problem is that after your first inner join there are only useres left that are also students. Because inner join is taking the cut-set of the joined tables:
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins
In the next innerjoin you are trying to get the cut-set of email addresses that are in the students and also teacher table. This will probably always be empty.
I recommend that you look up DB joins and I would use leftJoin for your use case.
->leftJoin('students', 'students.email' , '=', 'users.email')
->leftJoin('teacher', 'teacher.email' , '=', 'users.email')
Here are some good answers on the topic:
What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

Add join filter in Laravel Eloquent

I am a novice in Laravel.
I want to add a filter join through Laravel Eloquent model.
I have below relationship
user belongs to city
user has one restaurant
restaurant has many jobs
Now I want to fetch all jobs with a filter of city.
I tried couple of ways, but ended up in error, like:
$jobs = Job::where("date_time", ">=", $currentDate)->where("city.id", 50)->whereIn('job_status', ['upcoming', 'active'])->orderBy('start_date_time', 'desc')->get();
and the below one
$jobs = Job::with(['restaurant'])->where("date_time", ">=", $currentDate)->where("city.id", 50)->whereIn('job_status', ['upcoming', 'active'])->orderBy('start_date_time', 'desc')->get();
So, here how can I add join from job -> restaurant -> user -> city?
Thanks
Assuming you have city_id in your table
$jobs = DB::table('jobs')->with('restaurant')
->join('users', 'users.id', '=', 'restaurant.user_id')
->join('cities', 'users.id', '=', 'cities.user_id')
->where("table_name.date_time", ">=", $currentDate)
->where("cities.id", 50)
->whereIn('job_status', ['upcoming', 'active'])
->orderBy('table_name.start_date_time', 'desc')->get();
I have edited my answer hope it helps. If not please post your errors and table structure.
You can read about joins here: https://laravel.com/docs/6.x/queries#joins

How to join tables with more than one attribute match?

I am trying to turn my raw sql into laravel query builder and I encounter difficulty on how to join multiple tables using with many attributes match.
In this case, I want to join the table jr_h and jr_d with three attributes match (book,p_seq and staff_code) rather than one (book).
Raw sql:
$sql = "select from_time,to_time,t.staff_code,s.name_t as staff_name,t.book,t.p_code,t.p_seq,p.hrs1,s.img_file,
t.hrs_work,p.sharing_cnt as hrs_work, t.hrs_ot as hrs_ot from jr_d as t
inner join jr_h as p on(t.book=p.book and t.p_seq=p.p_seq and t.staff_code=p.staff_code)
inner join astaff as s on(t.staff_code=s.staff_code) ";
Laravel query builder:
$jr_d = DB::table('jr_d')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('astaff', 'jr_d.staff_code', '=', 'astaff.staff_code')
->select('jr_h.*','jr_d.*','astaff.*','astaff.name_t as staff_name')
->where('jr_d.ref_group','=','E')
->get();
and also want to know if there is a way to make the query faster since it has a lot of data in the tables.
Laravel joins with multiple conditions:
$results = DB::table('jr_d')
->select('jr_h.*','jr_d.*','astaff.*','astaff.name_t as staff_name')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('jr_h as p', function($query){
$query->on('t.book','=', p.book');
$query->on('t.p_seq','=', 'p.p_seq');
$query->on('t.staff_code', '=', 'p.staff_code');
})
->where('jr_d.ref_group','=','E')
->get();
`
Try this:
// ...
->join('jr_h p', function($join) {
$join->on('t.book', '=', 'p.book');
$join->on('t.p_seq', '=', 'p.p_seq');
// ... more conditions
});
Try this.
$jr_d = DB::table('jr_d')
->join('jr_h', 'jr_d.book', '=', 'jr_h.book')
->join('astaff', 'jr_d.staff_code', '=', 'astaff.staff_code')
->select('*','astaff.name_t as staff_name')
->where('jr_d.ref_group','=','E')
->get();

How to create SQL Join Statement in Laravel Controller

I have two table customer_id namely tbl_customer and tbl_stocks connected on the same database. My logic about this problem is JOIN sql statement.
This is for Laravel and MySQL, so far i've tried this on PHP and is working fine but when I implement it on laravel it is not working i wonder why?
here is my code in PHP and want to convert it to laravel but I dont know where to put? will i put it in the View or in the Controller
$query = "SELECT c.*, s.* FROM tbl_customer c JOIN tbl_stock s ON s.customer_id = c.customer_id AND c.customer_id = 1";
Controller
$data = DB::table('tbl_customer')
->join ...... //Im not sure about this
->select .... // neither this
->get();
print_r($data)
Model
I have no codes on my model
Routes
Route::get('/admin/shopcontrol', 'Admin\ShopsController#testquery');
I expect a result of fetching or getting the query or result of the values in just a simple echo and the fetch join is connected
Have you checked the Laravel site?
https://laravel.com/docs/5.7/queries#joins
It has a demonstration you could use to reorganize your code.
As it follows below from the site.
Joins
Inner Join Clause
The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Of course, as you can see, you can join to multiple tables in a single query:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
You may find more information there if it suits you.
Try this:
$data = DB::table('tbl_customer')
->join('tbl_stock', 'customer_id', '=', 'tbl_customer.customer_id')
->select('tbl_customer.*', 'tbl_stock.*')
->where('customer_id', '=', 1)
->get();

Laravel Eloquent - Select MAX with other columns

I'm trying to select a number of columns along with MAX. The raw query would be something like: SELECT users.id, ..., MAX(ur.rank) AS rank but I cannot figure out how to do it using the query builder supplied by Laravel in Eloquent.
This is my attempt:
$user = User::join('users_ranks AS ur', function($join) {
$join ->on('ur.uid', '=', 'users.id');
})
->where('users.id', '=', 7)
->groupBy('users.id')
->first(['users.id', 'users.username', 'MAX(ur.rank) AS rank']);
I simply cannot figure it out. What I want to achieve is I'm selecting a user where users.id = 7, and I'm wanting to select the MAX rank that's in users_ranks where their users_ranks.uid = users.id.
I was told to avoid sub-queries as when working with large result sets, it can slow things down dramatically.
Can anyone point me in the right direction? Thanks.
I think you should rewrite it like this:
DB::table('users')
->select(['users.id', 'users.username', DB::raw('MAX(ur.rank) AS rank')])
->leftJoin('users_ranks AS ur', 'ur.uid', '=', 'users.id')
->where('users.id', '=', 7)
->groupBy('users.id')
->first();
No sense to use User:: if you use table names later and want to fetch not all of the fields ( 'users.id', 'users.username' ).

Categories