I am trying to select and join to other table but my query having extra quote unintentionally.
I use this code:
$this->db->select('TA.*, TC.username user FROM tbl_actlog AS TA');
$this->db->join('(SELECT id, username FROM tbl_login) AS TC', 'TC.id = TA.account_id', 'LEFT OUTER');
$this->db->where('TA.date_log >=', $start_date);
$this->db->where('TA.date_log <=', $end_date);
But when my code runs it gives me an error and the output is:
SELECT `TA`.*, `TC`.`username user FROM tbl_actlog` AS `TA`
LEFT OUTER JOIN (SELECT id, username FROM tbl_login) AS TC
ON `TC`.`id` = `TA`.`account_id`
WHERE `TA`.`date_log` >= '2019-12-10' AND `TA`.`date_log` <= '2019-12-10'
ORDER BY `TA`.`act_id` DESC LIMIT 10
MySQL said: Documentation
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the
right syntax to use near 'LEFT OUTER JOIN (SELECT id, username FROM
tbl_login) AS TC ON `TC`.`id` = `TA`.`' at line 1
From what I understand the right query syntax should be:
$this->db->select('TA.*, TC.id, TC.username');
$this->db->from('tbl_actlog AS TA');
$this->db->join('tbl_login AS TC', 'TC.id = TA.account_id', 'LEFT OUTER');
$this->db->where('TA.date_log >=', $start_date);
$this->db->where('TA.date_log <=', $end_date);
You are not supposed to put the FROM inside your ->select() call. You can make a separate ->from($table_name) call or do ->get($table_name). See documentation.
try following code
$this->db->select('TA.*, TC.username user, TC.id login_id');
$this->db->from('tbl_actlog AS TA');
$this->db->join('tbl_login as TC', 'TC.id = TA.account_id', 'LEFT');
$this->db->where('TA.date_log >=', $start_date);
$this->db->where('TA.date_log <=', $end_date);
Related
I am using Laravel Framework 6.16.0.
I have the following sql query:
SELECT DISTINCT
`companies`.*
FROM
`companies`
LEFT JOIN `trx` ON `trx`.`companies_id` = `companies`.`id`
WHERE
`trx`.`transaction_date` >= 2020-11-12 AND companies.symbol NOT IN (SELECT DISTINCT
companies.symbol
FROM
`companies`
LEFT JOIN articles a ON a.companies_id = companies.id
WHERE
a.created_at >= 2020-11-12
ORDER BY
created_at
DESC)
ORDER BY
transaction_date
DESC
I have created the following eloquent query:
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', Carbon::today()->subDays(1)->startOfDay())
->orderBy('transaction_date', 'desc')
->distinct()
->get('symbol');
However, I am not sure how to pack the in my eloquent query to get all the symbol back that should be excluded.
I highly appreciate your replies!
You should try something like this:
$date = Carbon::today()->subDays(1)->startOfDay();
DB::connection('mysql_prod')->table('companies')->select('companies.symbol')
->leftJoin('trx', 'trx.companies_id', '=', 'companies.id')
->where('trx.transaction_date', '>=', $date)
->whereNotIn('companies.symbol', function ($q) use ($date) => {
$q->select('companies.symbol')
->from('companies')
->leftJoin('articles', 'articles.companies_id', 'companies.id')
->where('articles.created_at', '>', $date)
->distinct()
->get()
})
->orderBy('transaction_date', 'desc')
->distinct()
->get();
It will provide a similar query as you mentioned.
Reference from here.
Also, you can read how to write sub Query from Laravel docs.
Check this one more good answer for that what you need.
I'd like to get the difference between two dates on two tables. The uploads.published_at compared to the completed_guides.created_at
I keep getting an error which says:
SQLSTATE[42000]: Syntax error or access violation: 1582 Incorrect parameter count in the call to native function 'datediff' (SQL: select users.*,completed_guides.created_at as completed_at,uploads.published_at,datediff(HOUR, published_at, completed_at) from `users` inner join `uploads` on `users`.`id` = `uploads`.`user_id` inner join `completed_guides` on `uploads`.`id` = `completed_guides`.`upload_id` where `completed_guides`.`upload_id` = 2839 limit 10)
Here is my code. Any help would be appreciated.
$select = [
'users.*',
'completed_guides.created_at as completed_at',
'uploads.published_at',
'datediff(HOUR, published_at, completed_at) as date_diff'
];
return User::select(DB::raw(join(',', $select)))
->join('uploads', 'users.id', '=', 'uploads.user_id')
->join('completed_guides', 'uploads.id', '=', 'completed_guides.upload_id')
->where('completed_guides.upload_id', $this->id)
->take(10)
->get();
You can use Laravel Query Builder's whereRaw() like this:
return User::select(DB::raw(join(',', $select)))
->join('uploads', 'users.id', '=', 'uploads.user_id')
->join('completed_guides', 'uploads.id', '=', 'completed_guides.upload_id')
->where('completed_guides.upload_id', $this->id)
->whereRaw('datediff(uploads.published_at, completed_guides.completed_at) as date_diff')
->take(10)
->get();
To set the format of date you can use SQL method - date_format(date, format) like this:
->select(DB::raw("DATE_FORMAT(date_diff, '%b %d %Y %h:%i %p') as formatted_date_diff"));
See more about SQL Date Format
Hope this helps!
The one with units, is timestampdiff, not datediff.
timestampdiff(HOUR, published_at, completed_at) as date_diff
How to write my sql query in laravel 5.2, query is giving below
SELECT a.groupID, count( * ) AS totalCount, b.description
FROM devicelist AS a, devicegroup AS b
WHERE a.groupID = b.groupID
GROUP BY a.groupID
Try:
$query = DB::table('devicelist as a')
->join('devicegroup as b', 'a.groupID', '=', 'b.groupID')
->select(DB::raw('count(*) as user_count, a.groupID, b.description'))
->groupBy('a.groupID')
->get();
To make the report i need to write a join query. I wrote the join query in sql now, i need to write the same query in laravel 5.2.
My sql query is given below.
SELECT a.accountID, a.deviceID, b.description, a.timestamp, a.latitude, a.longitude, a.speedKPH as speed, a.heading, a.altitude, a.address, a.distanceKM as distance, a.odometerKM as odometer, a.IbatVolts, a.EbatVolts, a.ITempr, a.fuelLevel, a.inputState, a.IgnRuntime, a.GPSFixType, a.GPSPDOP, a.AlertType, a.speedLimitKPH, a.isTollRoad
FROM eventdata as a, device as b
WHERE a.deviceID = '$deviceID'
AND a.accountID = '$accountID'
AND a.timestamp >= $dt1
AND a.timestamp <= $dt2
AND a.deviceID=b.deviceID
ORDER BY timestamp DESC
and i tried to write it in laravel also. the query is given below
DB::table('device as b')
->join('eventdata as a', 'a.deviceID', '=', 'b.deviceID')
->where('a.deviceID', '=', '$deviceID')
->where('a.accountID', '=', '$accountID')
->where('a.timestamp', '>=', '$dt1')
->where('a.timestamp', '<=', '$dt2')
->select('a.accountID', 'a.deviceID', 'b.description', 'a.timestamp',
'a.latitude', 'a.longitude', 'a.speed', 'a.heading', 'a.altitude', 'a.address', 'a.distanceKM as distance', 'a.odometerKM as odometer', 'a.IbatVolts', 'a.EbatVolts', 'a.ITempr', 'a.fuelLevel', 'a.inputState', 'a.IgnRuntime', 'GPSFixType', 'a.GPSPDOP', 'a.AlterType', 'a.speedLimitKPH', 'a.isTollRoad')->get():
Is this right? Can anyone tell me and help me to write the correct query.
The join syntax in laravel 5.2 is:
$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();
and you are using the same. In case you are facing any issue than you can print the raw sql query by using:
DB::enableQueryLog();
// Your query
$queries = DB::getQueryLog();
print_r($queries); // it will print raw sql query in prepared statement style
I have the following Active Record pattern within one of my models :
$this->db->get('names');
$this->db->like('name', $name);
$this->db->where('ratio >=', 0.75);
$this->db->order_by('ratio', 'desc');
$query = $this->db->get();
This gives me a syntax error :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE `ratio` >= 0.75 AND `name` LIKE '%JORDAN%' ORDER BY `ratio' at line 2
The full statement being returned is :
SELECT * WHERE `ratio` >= 0.75 AND `name` LIKE '%JORDAN%' ORDER BY `ratio` desc
I don't know why my table names isn't showing as I'm calling $this->db->get('names'); which should produce SELECT * FROM names, is it just not returning in the error? What's wrong with this statement and what should I do to correct my Active Record call?
get needs to go at the end. If you want to select a table before - use $this->db->from('names'); and then just $this->db->get();. So the full code:
$this->db->like('name', $name);
$this->db->where('ratio >=', 0.75);
$this->db->order_by('ratio', 'desc');
$query = $this->db->get('names');
or the chaining version:
$query = $this->db->like('name', $name)
->where('ratio >=', 0.75)
->order_by('ratio', 'desc')
->get('names');
Using from:
$query = $this->db->from('names')
->like('name', $name)
->where('ratio >=', 0.75)
->order_by('ratio', 'desc')
->get();