Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

eloquent - How to use Nested functions substr(), cast() and Max() in query builder in laravel 8?

I posted this question yesterday but I think it's unclear so I deleted it and posted it again with more details. In my oracle database I have a USERS table with id_user defined as varchar and this varchar is like this: '145/1' ...... '145/9' so to add a new user I check the maximum value ('145/9') and add 1 to the second part of id_user (after the slash) so that the id_user is '145/10'.

The steps are like this:

  1. First: I'm using substr() to get the second part (after the slash) of all id_user.
  2. Second: I use Cast() to convert it to Int.
  3. Third: I use Max() to get the maximum value of Int numbers.

Finally in my laravel code I use the result of this query(the result is 9) and add 1 to it and insert a new user in the users table with id_user = '145/10' and so on. This query works fine but I need it in the Query Builder so I am trying a lot of queries but they didn't work.(please help me)

SELECT MAX(CAST(SUBSTR(id_user, INSTR (id_user, '/') + 1) AS INT)) AS Aggregate 
FROM "users" 
WHERE "ID_USER" LIKE '145/%';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Finally, this query gives me the correct maximum:

 DB::table('users')->select(DB::raw('MAX(CAST(SUBSTR(id_user,INSTR(id_user, '/') + 1) AS INT)) as max')) ->where('id_user','like','145'.'/%')->get()[0];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...