PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How can I convert int to string in laravel eloquent?

 April 19, 2022     laravel, laravel-eloquent, mysql, php, type-conversion     No comments   

Issue

My mysql query is like this :

SELECT b.id, b.name, COUNT(*) AS count_store
FROM stores a
JOIN locations b ON CONVERT(b.id,CHAR) = a.address->'$."regency_id"'
GROUP BY b.id
ORDER BY count_store DESC
LIMIT 10 

If mysql query I use this : CONVERT(b.id,CHAR) to convert int to string

How can I convert int to string in laravel eloquent? I'm using Laravel 5.3.

I had try like this :

$stores = Store::select('locations.name','COUNT(*) AS count_store')
               ->join('locations', 'locations.id', '=', 'stores.address->regency_id')
               ->groupBy('locations.id')
               ->orderBy('count_store', 'desc')
               ->limit(10)
               ->get();

But it does not work


Solution

If you want to use a very custom join condition, such as one involving a cast of one or both columns, then I'm not sure this would be possible without at least some kind of raw syntax. Hence, you should consider the answer given by @Rodrane as well as this one:

$stores = Store::select('locations.id', 'locations.name', DB::raw('COUNT(*) AS count_store'))
               ->join('locations', DB::raw("CONVERT(locations.id, CHAR)"), '=', 'stores.address->regency_id')
               ->groupBy('locations.id', 'locations.name')
               ->orderBy('count_store', 'desc')
               ->limit(10)
               ->get();

Note that I made the following changes:

  • Used DB::raw() to give a custom alias to the count
  • Added location.name to the GROUP BY (and select) clause
  • Used another DB::raw() to handle the cast in the join condition


Answered By - Tim Biegeleisen
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing