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;
}
Related
I am trying to configure a query within a Laravel app that is equivalent to this:
SELECT SUM(balance), name FROM db.statement_versions
INNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id
GROUP BY name;
This query works when I run it in MySQL Workbench, but when I try to translate it into PHP with the Laravel query builder I am getting an error. What I ultimately want is to return all accounts with their summed balance of statement_versions.balance. Here is my code right now:
public static function query(LensRequest $request, $query)
{
return $request->withOrdering($request->withFilters(
$query->select('accounts.name')->sum('statement_versions.balance')
->join('statements', 'statement_versions.statement_id', '=', 'statements.id')
->join('accounts', 'statements.account_id', '=', 'accounts.id')
->orderBy('balance', 'desc')
->groupBy('statement_versions.balance', 'accounts.name')
));
}
I have tried a couple different variations of this, but I get the error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'statement_versions.balance' in 'field list'. How can I solve this and get the query working correctly?
Not having your tables it will be a bit hard, but I hope that this will give you a path to what you want to achieve, it might be luck that it will work from the first shot :)
DB::table('statement_versions as sv')
->select([
'name',
DB::raw('sum(balance) as total')
])
->join('statements as s', 'sv.statement_id', '=', 's.id')
->join('accounts as a', 's.account_id', '=', 'a.id')
->groupBy('name');
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')
I'm trying to get rings from the database. but only filter is the homepage is 1 or 0.
I only need the rows where homepage is 1.
This is what i tried
$ringen = RingKoppelCategory::with('ringen')->get()->where('homepage', '=' , 1);
returns null
And when i put the ->get() at the end of the query builder it checks the ringkoppelcategory table for a homepage which is not what i want it to do.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'homepage' in 'where clause' (SQL: select * from `ringkoppelcategory` where `homepage` = 1
I need to get the rings relationship from the ringkoppelcategory, but only the rings where the homepage is 1.
You need to use a function to pass along a where within your with.
$ringen = RingKoppelCategory::with(['ringen' => function ($query) {
$query->where('homepage', '=' , 1);
}])->get();
More information is found in the documentation
I think you need to use the following query
$ringen = RingKoppelCategory::whereHas('ringen', function ($query) {
$query->where('homepage', '=', 1);
})->get();
Check Querying Relationship Existence section at documentation
I'm trying to fetch records with an array of exceptions, here's what I tried (refer below)
$users_nowishlist = DB::table('employee')
->join('users', 'users.employee_id', '=', 'employee.employee_id')
->where('has_wishlist', '=', "0")
->whereNotIn('employee_id', ['MMMFLB003', 'guest_01', 'guest_02', 'guest_03'])
->where('employment_status', '=', 'ACTIVE')
->get();
so in this line was my records filter, means only records that does not equal to any of those 'employee_id' from the exceptions array will be return (refer below)
->whereNotIn('employee_id', ['MMMFLB003', 'guest_01', 'guest_02', 'guest_03'])
but instead I got this error (refer below):
SQLSTATE[23000]: Integrity constraint violation: 1052 Column
'employee_id' in where clause is ambiguous (SQL: select * from
employee inner join users on users.employee_id =
employee.employee_id where has_wishlist = 0 and employee_id
not in (MMMFLB003, guest_01, guest_02, guest_03) and
employment_status = ACTIVE)
any ideas, help please?
This happens because when you are doing the join there are two columns with the same name.
That's why on your join you prefix the employee_id with users. and employee.
Now on your whereNotIn you also have to prefix it, so the query engine knows which table column you are trying to reference. So you only have to add the prefix in your whereNotIn clause:
->whereNotIn('employee.employee_id', ['MMMFLB003', 'guest_01', 'guest_02', 'guest_03'])
->whereNotIn('employee.employee_id', ['MMMFLB003', 'guest_01', 'guest_02'])
when using join , these errors are expected if you have two fields have the same name in the tables you join between, so always try to fetch them like this
table_name.field_name
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.