Laravel DB Join with asterisk and alias select - mysql

I am trying to get following query on Laravel:
SELECT
table1.* ,
table1.colb as aaa
FROM
table1
LEFT jOIN table2 on table2.cola = table1.colb
This is the Laravel DB Query code :
DB::table('table1')
->leftJoin('table2','table2.cola', '=', 'table1.colb')
->select('table1.* , table1.colb as aaa')
->get();
But it doesn't work and I get SQL Syntax error.
This is the SQL which Laravel is making using above code which is wrong :
select `table1`.* as `table1.colb`
from `table1`
left join `table2` on `table2`.`cola` = `table1`.`colb`
How can I fix this using laravel way?

You need to pass multiple parameters to the select method for each one to get prepared correctly:
DB::table('TABLE1')
->leftJoin('TABLE2','TABLE2.COLA', '=', 'TABLE1.COLB')
->select('TABLE1.*', 'TABLE1.COLB AS AAA') // <- 2 separate params here
->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

Laravel 5.8, Tricky subquery with Count(*) in where clause

I need to write a little tricky subquery in where clause
So, I have a query like this
Select * FROM table1
JOIN table2 ...
LEFT JOIN table3 ...
WHERE (SELECT COUNT(*) FROM some_table where some_condition) = 0;
The SQL works fine, but how can I move it into the Laravel?
Yeah, I know that I should use DB::raw() but the problem is the subquery returns count. So, for example, the count is 5454. After that, I'm having something like this.
->where(5454, '=', 0)
and it gives me obvious error message: Unknown column 5454 ...
I've tried also to use AS count for the subquery but in that case, I'm having another obvious error message: Syntax error 0_0
So, any suggestions?
Try
whereRaw("(SELECT COUNT(*) FROM some_table where some_condition) = 0")
This will help you.

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

Symfony2 - subquery within a join error

I would like to use a subquery inside a join, however Symfony2 throws the following error:
Here is my failed attempt:
$query = $em->createQuery(
'SELECT
sc.id AS id,
u.id AS userId,
u.username AS username,
sc_count.upvotes
FROM
myBundle:SuggestedCar sc
INNER JOIN myBundle:User u WITH sc.user_id = u.id
INNER JOIN ( SELECT sc1.user_id, COUNT(sc1.id) AS upvotes
FROM myBundle:SuggestedCar sc1
GROUP BY sc1.user_id
) sc_count WITH u.id = sc_count.user_id'
);
Basically I'm just joining 3 tables and the third one has a count. The query worked when executing it inside the database.
How would it be possible to use a SELECT statement inside a join? Is it a good idea to use raw SQL at this point?
The $em->createQuery() function is expecting DQL as the parameter, not SQL. If you want to execute a raw SQL statement, the syntax is different. You can do it like this:
$sql = "SELECT * FROM my_table";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
for more on DQL or querying for objects, see Querying for Object. The biggest difference is DQL will return an object (based on your entity classes in Symfony). The method I posted above will just give you a PDO result. So if you execute raw SQL, don't expect to be able to use the result as an object.
If you want to use raw SQL and still have the result mapped to an object, you can look at the doctrine docs about Result set mapping. In my opinion, this is more work than necessary.

Need a SQL to Laravel Eloquent Translation

I need to translate the following SQL query into Laravel's Eloquent syntax:
SELECT a.*
FROM applications a
LEFT JOIN ratings r
ON a.id = r.application_id
AND r.admin_id = 1
WHERE r.admin_id IS NULL
The only way I've been able to get it to work is running the query using DB::raw, but I'm curious how it should look when using the Eloquent syntax. Ideally, I'd like to be able to migrate to any other database without a hiccup.
You can pass a closure to a join. You need to use DB::raw() as you're specifying a variable, rather than another database column to join on.
DB::table('applications')
->select('applications.*')
->leftJoin('ratings', function($join)
{
$join->on('ratings.application_id', '=', 'applications.id');
$join->on('ratings.admin_id', '=', DB::raw('1'));
})
->whereNull('ratings.admin_id')
->get()