0

This is my database table

$reports = DB::table('attendance_report_details')
            ->select('*','project_hours[$index_id]')
            ->get();

I am passing index id to the function. Is there a way to do it like this?

6
  • Possibly. But why are you storing your data in a non-relational format like this? Commented Nov 14, 2018 at 9:20
  • I am storing the data as json ecoded data Commented Nov 14, 2018 at 9:39
  • I know you are, I can see that. My question was why are you doing it like that, rather than creating a proper relational structure? Commented Nov 14, 2018 at 10:40
  • Because the project hour is related to a corresponding project.The sequence of project may differ for each att_rep_id.Also, old projects may be deleted. So its needed to store it like this. Commented Nov 14, 2018 at 11:16
  • None of that stops you from making a proper structure using separate tables and foreign keys. If you did that you could have many-to-many relationships linking the employee table to the project table via a project hours table which stores the hours, and foreign keys to the employee and projects tables. Then writing queries to get particular hours is trival using SQL. Maybe you first need to study database design in more detail if you didn't realise this kind of thing? Commented Nov 14, 2018 at 11:20

1 Answer 1

1

Use the arrow operator (MySQL-only):

$reports = DB::table('attendance_report_details')
    ->select('*', DB::raw("project_hours->'$[".(int) $index_id."]'"))
    ->get();

Or its alias JSON_EXTRACT() (MySQL & MariaDB):

$reports = DB::table('attendance_report_details')
    ->select('*', DB::raw("json_extract(project_hours, '$[".(int) $index_id."]')"))
    ->get();
Sign up to request clarification or add additional context in comments.

3 Comments

Nope.. :( I am getting an error. For the first solution the error is "Syntax error or access violation: 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 '>'$[1]' from attendance_report_details' at line 1"
For the second solution: json functions can be used only in mariaDB version 10.2.3 and above . My version is 10.1.36. I am using xampp
Anyways, thanks for your answer :) @Jonas Staudenmeir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.