I have the following tables:
main
id
user_id
host_id
users
id
room_id
hosts
id
room_id
rooms
id
number
As you can see both users and hosts are connected with table rooms. Unfortunately users.room_number = 1, and hosts.room_number = 2. How can I create a query using leftJoin in laravel to distinguish between users.room_number and hosts.room_number? And then how I can refer to each room_number in my foreach loop?
I have something like this:
MainController.php
$main = DB::table('main')
->leftJoin('users', 'users.id', '=', 'main.user_id')
->leftJoin('hosts', 'hosts.id', '=', 'main.host_id')
->leftJoin('rooms as users_rooms', '=', 'rooms.id', 'users.room_id')
->leftJoin('rooms as hosts_rooms', '=', 'rooms.id', 'hosts.room_id')
->select('users_rooms.number as u_rooms_number', 'hosts_rooms.number as
h_rooms_number')
->get();
return view('main.index', ['main' => $index]);
main/index.blade.php
#foreach($main as $element)
{{ $element->u_rooms_number }}
{{ $element->h_rooms_number }}
#endforeach
Because of both leftJoin with 'rooms as users_rooms' and 'rooms as hosts_rooms' I get an Error "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rooms.id' in 'on clause'".
You get the error message, because you join twice on the rooms table. Your on clause therefore cannot identify which table of the two is specified with 'rooms.id'.
To avoid the conflict you correctly renamed the table joins in your query. Therefore you can use the names as if they were the tables themself.
->leftJoin('rooms as users_rooms', '=', 'users_rooms.id', 'users.room_id')
->leftJoin('rooms as hosts_rooms', '=', 'hosts_rooms.id', 'hosts.room_id')
Related
QueryException in Connection.php line 729:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'site_name' in
'where clause' (SQL: select email_date, url, recipient from
report_list where site_name = mywebsite)
$records = DB::table('report_list')
->select('email_date','url','recipient')
->where('site_name',$site_name)
->get();
return records;
return view('monthlyReport')
->with('records',$records)
->with('site_name',$site_name);
My site_name was on different table and I don't know if I need to put Join or Make a model for this two.
Can someone help me with this query?
First of all You need to add column named "site_name" to your "report_list" table in database.
this query is for you to join 2 tables (here I took example "users" table as second table If your second table is defferent use your) ->
$records = DB::table('report_list')
->join('users', 'report_list.user_id', '=', 'users.id')
->where('report_list.site_name', '=', $site_name);
->select('users.*', 'report_list.email_date','report_list.url','report_list.recipient')
->get();
return view('monthlyReport')
->with(['records' => $records , 'site_name' => $site_name ]);
If you show the tables to see the columns and table names could help you better, while these are some examples:
//Option 1
$results = DB::table('users')
->join('business', 'users.id', '=', 'business.user_id')
->select('users.*', 'business.name', 'business.telephone', 'business.address')
->get();
//Option 2
$results = User::join("business as b","users.id","=","business.user_id")
->select(DB::raw("users.*"), "b.name as business_name", "b.telephone as business_telephone", "b.address as business_address")
->get();
The laravel docs: https://laravel.com/docs/5.6/queries#joins
You should create a model for your other table which I assume it's Site then in the report_list model create a relation method like :
public function sites(){
return $this->hasOne(Site::class);
}
or:
public function sites(){
return $this->hasOne('App\Models\Site);
}
After that in your eloquent query use this :
$records = DB::table('report_list')
->select('email_date','url','recipient')
->whereHas('sites', function($query){
$query->where('site_name',$site_name);
})
->with('sites')
->get();
I considered an issue when viewing data called from database using two related tables users and roles which have this structure:
the users.role column contains an integer referring to the role record of roles table
the roles.name column contains the role name i.e. (user / admin / editor)
in my controller I used the laravel docs to build my query as I need to show a table in blade that holds users.name , users.email and roles.name that related to user by the schema:
$users = DB::table('users')
->join('roles', 'users.role', '=', 'roles.id')
->select('users.name', 'users.email', 'roles.name')
->get();
actually it works and dumping data, but the issue is the confusion of the two name alike cols users.name and roles.name. it dumping only the roles.name value like this sample record:
{"name":"user","email":"user#asd.com"},{"name":"user","email":"new#asd.com"},{"name":"user","email":"jaeden93#example.org"}
even when I tried to select all cols of users table like below:
$users = DB::table('users')
->join('roles', 'users.role', '=', 'roles.id')
->select('users.*', 'roles.name')
->get();
the users.name col still not showing!
Is there a way to solve this issue without changing table's column titles ?
You can give an alias to the column, to avoid problems with the same name
Use this
$users = DB::table('users')
->join('roles', 'users.role', '=', 'roles.id')
->select('users.*', \DB::raw('roles.name as role_name'))
->get();
It's the same to do this in SQL
SELECT users.*, roles.name as role_name FROM ...
I have three tables. work_orders, customers, and aircraft. In the work_orders table there are two fields customer_id and aircraft_id. I'm trying to retrieve the customers and aircraft data through the use of join. I am getting an array of errors, but they all seem to be pointed in the same direction and that is that the table cannot be found.
Here is my WorkOrderController index:
public function index(WorkOrder $workorder)
{
$workorder_array = $workorder
->join('work_orders as work', 'work.aircraft_id', '=', 'aircraft.id')
->join('work_orders as workorder', 'workorder.customer_id', '=', 'customers.id')
->select('work_orders.opened_date', 'customers.mobile', 'aircraft.year')
->get();
return view('work-orders.index', compact('workorder_array'));
}
And with this I get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'aircraft.id' in 'on clause' (SQL: select work_orders.opened_date from work_orders inner join work_orders as work on aircraft.id = work.aircraft_id inner join work_orders as workorder on workorder.customer_id = customers.id)
I've tried switching work.aircraft_id with aircraft.id, because the Laravel Docs show it in that order, but that doesn't make any difference either. The only way I can get rid of this error is to remove my join statements.
I had the wrong table in the join statement. Here's what I should have had:
public function index(WorkOrder $workorder)
{
$workorder_array = $workorder
->join('aircraft', 'work_orders.aircraft_id', '=', 'aircraft.id')
->join('customers', 'work_orders.customer_id', '=', 'customers.id')
->select('*')
->get();
return view('work-orders.index', compact('workorder_array'));
}
I'm trying to fetch following things from the database:
user name
user avatar_name
user avatar_filetype
complete conversation_messages
with the following query:
static public function getConversation($id)
{
$conversation = DB::table('conversation_messages')
->where('belongsTo', $id)
->join('users', 'conversation_messages.sender', '=', 'users.id')
->join('user_avatars', 'conversation_messages.sender', '=', 'user_avatars.id')
->select('users.name', 'conversation_messages.*', 'user_avatars.name', 'user_avatars.filetype')
->get();
return $conversation;
}
It works fine so far, but the avatar's column name is 'name' like the column name from the 'users' table.
So if I'm using this query the to get the output via $conversation->name, the avatar.name overwrites the users.name
Is there a way to rename the query output like the mysql "as" feature at laravel 5.1?
For example:
$conversation->avatarName
$conversation->userName
Meh okay.. i've found a simple solution here
->select('users.name as userName', 'conversation_messages.*', 'user_avatars.name as avatarName', 'user_avatars.filetype')
As you can mention I've added the requested "as-Feature" next to the table.columnName
Take a look at this example of trying to join three tables staffs, customers and bookings(pivot table).
$bookings = \DB::table('bookings')
->join('staffs', 'staffs.id' , '=', 'bookings.staff_id')
->join('customers', 'customers.id' , '=', 'bookings.customer_id')
->select('bookings.id', 'bookings.start_time', 'bookings.end_time', 'bookings.service', 'staffs.name as Staff-Name', 'customers.name as Customer-Name')
->orderBy('customers.name', 'desc')
->get();
return view('booking.index')
->with('bookings', $bookings);
I had the following problem, simplified example:
$result = Donation::join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
$result is a collection of Donation models. BUT CAREFUL:
both tables, have a 'created_at' column. Now which created_at is displayed when doing $result->created_at ? i don't know. It seems that eloquent is doing an implicit select * when doing a join, returning models Donation but with additional attributes. created_at seems random. So what I really wanted, is a return of all Donation models of the user with email hello#papabello.com
solution is this:
$result = Donation::select('donation.*')->join('user', 'user.id', '=', 'donation.user_id')->where('user.email', 'hello#papabello.com')->first();
Yeah, simply rename the column on either table and it should work.
Also what you can do is, rename the user.name column to anything, also rename sender column of conversation_messages to id and perform a natural join.
I have two tables in Laravel connected with a pivot table. The two tables are users and roles, and the pivot table is called role_user. The pivot table also contains two extra fields: start and stop. This way I can track which roles a user has had in the past.
Now I want to create a query that gets all users who currently have role_id = 3.
First I had used WherePivot, but apparently that is bugged.
I have now made the following query using Eloquent:
Role::with('User')
->where('id', '=', '3')
->where('role_user.start', '<', date('Y-m-d'))
->where('role_user.stop', '>', date('Y-m-d'))
->whereHas('users', function($q){
$q->where('firstname', 'NOT LIKE', '%test%');
})
->get();
But somehow I am getting an error that the column start of the pivot table cannot be found. But I can confirm in PHPMyAdmin that the column is there.
This is the entire error:
Illuminate \ Database \ QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'klj_role_user.start' in 'where clause' (SQL: select * from `klj_roles` where `id` = 3 and `klj_role_user`.`start` < 2014-06-02 and `klj_role_user`.`stop` > 2014-06-02 and (select count(*) from `klj_users` inner join `klj_role_user` on `klj_users`.`id` = `klj_role_user`.`user_id` where `klj_role_user`.`role_id` = `klj_roles`.`id` and `firstname` NOT LIKE %test%) >= 1)
Can someone tell me if I am doing something wrong or give me a hint where I should be looking now?
The error is telling you that you are missing the start column in your pivot table klj_role_user. What you should do is create the column. If the column is already there, ensure you are using the correct database.
I've also simplified your query a little bit. You don't really need a whereHas because you aren't trying to limit your roles by the users associated, but by the id, which in this case, you are using 3. A with() would work perfectly fine and wherePivot() seems to be working fine for me when used in conjunction with with().
$role = Role::with(array('users' => function($q)
{
$q->wherePivot('start', '>', date('Y-m-d H:i:s'));
$q->wherePivot('stop', '<', date('Y-m-d H:i:s'));
$q->where('firstname', 'NOT LIKE', '%test%');
}))->find(3);
foreach($role->users as $user) {
echo $user->firstname;
}