1

I have query of data which some of it's data needs to be array but not sure how to get those arrays inside my query.

Screenshot

one

I have 2 students in 2 semester and 4 different classes what I try to achieve is to get each student semester and classes in array.

So I would have results such as this:

two

code

$students = DB::table('schools')
            ->where('schools.id', $id)
            ->join('school_semesters', 'school_semesters.school_id', '=', 'schools.id')
            ->join('semester_classes', 'semester_classes.semester_id', '=', 'school_semesters.id')
            ->join('class_students', 'class_students.class_id', '=', 'semester_classes.id')
            ->join('users', 'users.id', '=', 'class_students.user_id')
            ->select(
                'school_semesters.name as semester',
                'semester_classes.name as class',
                'users.name as students',
                'users.id as id'
            )
            ->groupBy('users.id') // return results as screenshot #2
            ->get();

Any idea?

Update

expected result would be something like this:

semester: ["Winter semester", "Our Spring semester"]
class: ["A1", "B1"]
students: "Student Two"
id: 5
DT_RowId: 5

so semester and class will be array.

3
  • 1
    so your question is how to convert your query result into an array? Commented Mar 11, 2020 at 8:52
  • @Gamopo only semester and classes otherwise it is array already, (each user will have 2 arrays inside it's data) Commented Mar 11, 2020 at 8:53
  • I'm not sure I understand what your question is, can you add (in code style) what output you expect from the DB query? Commented Mar 11, 2020 at 9:02

1 Answer 1

1

You're doing a group by user.id. by using Group concat you'll get the expected result.

->select(
    \DB::raw('group_concat(DISTINCT school_semesters.name) as semester'),        
    \DB::raw('group_concat(DISTINCT semester_classes.name) as class'),
    'users.name as students',
    'users.id as id'
)
Sign up to request clarification or add additional context in comments.

2 Comments

Column not found: 1054 Unknown column 'GROUP_CONCAT(school_semesters.name)' in 'field list'
Check I've updated with DB::raw query. check last updated query.

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.