Search code examples
laravelmodelsexplode

Laravel 5 model field explode to link to other models


I have a field in my master table with a field called data which has ids stored like 0005,0006,0010 which are keys for records to be extracted from another table called table1. It's kinda like a belongsToMany except it's not broken into individual records, but same functionality.

I'm wondering how to explode master.data field off the comma and return the records for table1 in the model. In this example, I'm wondering how to return table1.* where table1.id=0005 or 0006 or 0010.

If I was to call it, it would be something like auth()->user()->master()->table1() with 5,6,10 in that array


Solution

  • You can do it by whereIn method. First you have to fetch the row from master table. I assume the row id 5 which has the column named data containing value 0005,00006,0010

    $master = DB::table('master')->where('id',5)->select('data')->get();
    // it returns "0005,0006,0010"
    
    $users = DB::table('table1')->whereIn('id',[$master])->get();
    // it will return all rows which has id 0005, 0006 and 0010
    

    Remember: The second argument of whereIn must be an array.