Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array datatype from database to eloquent laravel

I have data stored in a database with a column data type of array. I can get the value in PostgreSQL as follows:

select id, student, subject[1] as first_subject, subject[array_length(subject, 1)] as last_subject
from tableinfo

So, I need to get the first and last value of the array in the Laravel eloquent query. But using select in eloquent doesn’t seem to work.

Eloquent query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

DB::Table('tableinfo')
->select('id', 'name', 'subject[array_length(subject, 1)] as last_subject')
->get();

Error message I got:
enter image description here

>Solution :

You can not use custom/raw select using select method, but you can use selectRaw method like below:

DB::Table('tableinfo')
->select('id', 'name')
->selectRaw('subject[array_length(subject, 1)] as last_subject')
->get();

above code will generate query like below:

select "id", "name", subject[array_length(subject, 1)] as last_subject from "tableinfo"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading