Laravel7 Join Syntax error or access violation - mysql

I am trying to write a query where I am joining a messages table and a users table so I can get all messages for a specific user and get the name of the user each message was from.
Here is my query
$inboxrow = DB::table('inbox_messages')
->join('inbox_messages', 'inbox_messages.to_userid', '=', Auth::id())
->join('users', 'users.from_userid', '=', 'inbox_messages.from_userid')
->select('inbox_messages.*', 'users.name')
->get();
My issue is the above gives me an error (see below) and not sure how to re-write my query to get what I need. Which is everything from the inbox_messages table where the to_userid equals the logged in persons userid and then get the name of the person who sent the message from the users table where the value of the column inbox_messages.from_user = the value from the column users.id
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias:
'inbox_messages' (SQL: select `inbox_messages`.*, `users`.`name` from `inbox_messages`
inner join `inbox_messages` on `inbox_messages`.`to_userid` = `3` inner join `users`
on `users`.`from_userid` = `inbox_messages`.`from_userid`)

Please, try with the below solution. Where I change extra join to where clause.
$inboxrow = DB::table('inbox_messages')
->join('users', 'users.from_userid', '=', 'inbox_messages.from_userid')
->select('inbox_messages.*', 'users.name')
->where('inbox_messages.to_userid', '=', Auth::id())
->get();

Related

Laravel duplicates join on production

I have a code where Eloquent query builder joins the ManyToOne tables articles and users.
The code looks like:
$model = Article::with('user')->select('articles.*'));
and then the model filters the user name
$model = $model->join('users', 'articles.user_id', '=', 'users.id')
->where('users.name', 'like', "%$value%");
This throws me an error:
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique
table/alias: 'users' (SQL: select count(*) as aggregate from
articles inner join users on articles.user_id = users.id
inner join users on articles.user_id = users.id where
users.name like %may% and users.name like %may% and
articles.deleted_at is null)
Look at the duplicate inner join on users table and also duplicate where clause.
The same code on localhost works fine and create sql:
select count(*) as aggregate from `articles` inner join `users` on `articles`.`user_id` = `users`.`id` where `users`.`name` like '%may%' and `articles`.`deleted_at` is null
Original code is here: https://github.com/camohub/laravel-datagrid-example/blob/master/app/Http/Controllers/DefaultController.php#L25
and the live error is here: https://laravel-datagrid.tatrytec.eu/?chgrid-filter-username=may&chgrid-perPage=25
I dont understand. It looks like some database setting is wrong.
Hope somebody knows what happened there. Thanks a lot.
EDIT: The issue is caused by PHP version. Production is lower 7.4.3 than localhost 7.4.19
The solution is to write an envelope above the Eloquent query builder. Here it is https://github.com/camohub/laravel-datagrid/blob/master/src/QueryBuilder.php

#1054 - Unknown column with backticks

I get 1054 - Unknown column error when I use backticks in where clause with mysql
`roles`.`id`
but it works fine with
'roles.id'
Any idea why and how to solve it? I need to make it work with backticks to make use of the Laravel Eloquent query builder.
select *
from `users` inner join `role_user` on `users`.`id` = `role_user`.`user_id`
where `roles`.`id` = `role_user`.`role_id` and (`users`.`id` = 8) and `users`.`id` = 8
Laravel - Eloquent query:
Policy::whereHas('role.users', function ($query) use ($user_id) {
$query->where([
'users.id' => $user_id
])->get();
});
As stated by #Barmar my query was missing a roles table in the FROM or JOIN clauses.
Since I have this error because the query was generated from Laravel - Eloquent I am posting my solution for future reference.
Policy::whereHas('role.users', function ($query) use ($user_id) {
$query->where([
'users.id' => $user_id
]);
})->get();
The problem was because I misplaced the get in the query builder inside whereHas instead of the outermost the query builder.

converting from simple mysql to Laravel query constructor

#forpas guys, I need to the query into laravel constructor.
this is what I tried.
$cates = DB::table('categories')
->select(DB::raw('categories.category_id, categories.category_title, categories.created_at, COUNT(task.task_id) AS counted_tasks'))
->leftJoin('tasks', 'categories.category_id', '=', 'tasks.task_cat_id')
->get();
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select categories.category_id, categories.category_title, categories.created_at, COUNT(task.task_id) AS counted_tasks from categories left join tasks on categories.category_id = tasks.task_cat_id)
Where I can see the final query of the constructor?
You're missing the groupBy. Try this code below:
$cates = DB::table('categories')
->select(DB::raw('categories.category_id, categories.category_title, categories.created_at, COUNT(task.task_id) AS counted_tasks'))
->leftJoin('tasks', 'categories.category_id', '=', 'tasks.task_cat_id')
->groupBy('categories.category_id, categories.category_title, categories.created_at')
->get();

Laravel 5.3 query builder access violation on group by

I have been using Laravel 5 for a week and I've now come to the point where I want to convert all my existing raw SQL queries using Query Builder but I have a problem.
When I run the following query, I get this error message
SQLSTATE[42000]: Syntax error or access violation: 1055
'procurement.pp_proposals.title' isn't in GROUP BY
$proposals = DB::table('tableA')
->join('tableB', 'tableA.id', '=', 'tableB.id')
->leftJoin('tableC', 'tableA.id', '=', 'tableC.id')
->select(DB::raw('tableA.id, title, date_created, date_completed, percent_complete, complete, COALESCE(COUNT(tableC.id), 0) AS total_ids'))
->where([
['tableB.user', '=', Auth::user()->username],
['submitted', '=', '0'],
])
->groupBy('tableA.id')
->orderBy('title', 'asc')
->get();
This is my raw SQL that works perfectly fine so I don't understand why i need to GROUP BY on all the extra columns
SELECT tableA.id,
title,
date_created,
date_completed,
percent_complete,
complete,
COALESCE(COUNT(tableC.id), 0) AS 'total_ids'
FROM tableA
INNER JOIN tableB
ON tableA.id = tableB.id
LEFT JOIN tableC
ON tableA.id = tableC.id
WHERE submitted = '0' AND tableB.user = 'user'
GROUP BY tableA.id
ORDER by title ASC
I am not sure how it works but surely you can fix that issue by setting strict = false on the config/database.php file to your MySQL config!
I had the same issue and setting it to false solve my problem!
Actually I just opened a question here to find why it happens!
If you want to follow: Strict database config Laravel 5.2 to Laravel 5.3

Zend_Db_Select - Joins and Count - Possible Zend Bug?

I'm having an issue getting a COUNT() from a SQL query using Zend_Db_Table_Select, and I think it may be a possible bug because the SQL it should be generating actually works. Here's the Zend Select Query: ($this is a Zend_Db_Table, renamed to table1 in this example)
$select = $this->select();
$select->setIntegrityCheck(false);
// Select Count
$select->from($this, array("COUNT(*) as 'COUNT'"))
->joinLeft('users', 'table1.userID = users.userID')
->joinLeft('table2', 'users.anotherKey = table2.anotherKey');
// Add Where clause after join
$select->where('users.anotherKey = ?', $anotherKeyValue);
This gives the error:
SQLSTATE[42000]: Syntax error or access violation: 1140
Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is
illegal if there is no GROUP BY clause`
However, this query...
SELECT COUNT(*) AS 'count' FROM table1
LEFT JOIN users ON table1.userID = users.userID
LEFT JOIN table2 ON users.anotherKey = table2.anotherKey
WHERE users.anotherKey = [anotherKeyValue]
...returns the expected results with no errors when run against the database. Any ideas whats going on, why the error, and how to get around it?
have you tried to see actual query, that zend_db produce?