Laravel/Eloquent whereIn/where with a pair of sets

Viewed 320

I have 3 tables in my database.

The first two tables are just normal tables with an ID and some other columns like:

Table 1

ID col01
1 ...
2 ...

Table 2

ID col01
1 ...
2 ...

The third table is some kind of a relation/assignment table:

Table 3

ID table1_id table2_id text
1 1 1 ..
2 1 2 ..
3 1 3 ..
4 2 1 ..
5 3 3 ..

Now I do have a SQL statement which does exactly what I want:

SELECT * FROM table_3 where (table1_id, table2_id) in ( (1, 1), (2, 1), (3, 3));

So Im sending following Request Body to the API:

   {
        "assignments": [
            {
                "table1_id": 1,
                "table2_id": 1
            },
            {
                "table1_id": 2,
                "table2_id": 1
            },
            {
                "table1_id": 3,
                "table2_id": 3
            }
        ]
    }

I do validate my the request with

->validate($request, 
[         
    'assignments' => 'required|array',
    'assignments.*.table1_id' => 'required|integer|min:1|max:20',
    'assignments.*.table2_id' => 'required|integer|min:1|max:20' 
]

Now Im kinda stuck how to use the eloquent commands (e.g. whereIn) to get my desired output.

Thanks in advance!

EDIT

So I took the workaround of arcanedev-maroc mentioned here: https://github.com/laravel/ideas/issues/1021

and edited it to fit my Request.

Works like a charm.

2 Answers

Laravel does not provide any functions by default. The core team said that they would not maintain this feature. You can read the post here.

But you can create your own query to accomplish this. I am providing a function that you can use as per your specification:

public function test(Request $request)
{
    $body=$request->input('data');
    $data=json_decode($body)->assignments;
    $query='(table1_id, table2_id) in (';
    $param=array();
    foreach($data as $datum)
    {
        $query=$query."(".$datum->table1_id.",".$datum->table2_id."), ";
    }
    $query = rtrim($query, ", ");
    $query = $query.")";
    $result=DB::table('table3')->whereRaw($query)->get();
    return $result;
}
Related