John Davidson

php - How to use whereIn for column array?

0 comments
Message:


I have data from a table structured like so:


table: students
{
id:
name:
classes: [
{
name: "gym"
},
{
name: "science"
},
{
name: "math"
},
{
name: "english"
}
]
}
reference array: science, math

How do I return only records that match the values found in the reference array. For example, if the reference array contains math and science then all records returned from the student table will need to have those values in the classes array name field.


I'm trying to use whereIn, but it does not accept a column (array) and field as the first parameter.



My Answer:
You can achieve this by using the `where` method with a closure to filter the records based on the values in the `classes` array. Here's an example code snippet:

php
$referenceArray = ['science', 'math'];

$students = DB::table('students')
->where(function ($query) use ($referenceArray) {
foreach ($referenceArray as $value) {
$query->whereJsonContains('classes', ['name' => $value]);
}
})
->get();

foreach ($students as $student) {
echo $student->name . "\n";
}


In this code snippet, we are using the `where` method with a closure to iterate over the values in the reference array and filter the records based on whether the `classes` array contains the specified value. The `whereJsonContains` method is used to check if the `classes` array contains the specified value in the `name` field.

This should return only the records that have both "science" and "math" in the `classes` array.

Rate this post

4 of 5 based on 2401 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us