Mugluck Mugluck - 29 days ago 10
MySQL Question

How do I complete this explode & comparison query properly? Laravel 5.3

I'm trying to get this string of tags and iterate through it to get the respective tag's collumns on another table:

1A-3,1-1,1-2,3-4,4-6,4-8,6-13,6-15,8-6,8-11,7A-4,7A-5,7A-6

Checks against:
enter image description here

$ministry = AgencyLogin::find(196);
$prefs = $ministry->Ministry_Preferences;
$tags = explode(',', $prefs);
foreach ($tags as $tag) {
$sub_categories[] = DB::table('descriptor')
->where('tag', $tag)
->select('subcategory', 'description')
->first();
}
//dd($sub_categories);
return view('agencydash', compact('sub_categories'));


dd($prefs)
prints the correct string.
$sub_categories[]
never converts to an actual array, so can't be parsed like one, and my limited experience in Laravel means I don't know how to turn a query like this into an array instead the current thing it is, an object.

dd($sub_categories)
after I treat it as an object prints a single result which seems to be random:

{#262 ▼
+"subcategory": "SUPPORT ROLE"
+"description": "Project Management"
}


I've been teaching myself Laravel and php steadily, so problems like this open more questions then I can answer yet.
Anybody know what I'm missing?

Answer

Why are you iterating through $tags and not using whereIn method and getting a whole collection of relevant rows?

$ministry = AgencyLogin::find(196);
        $prefs = $ministry->Ministry_Preferences;
        $tags = explode(',', $prefs);
        $sub_categories = DB::table('descriptor')
            ->whereIn('tag', $tags)
            ->get(['subcategory', 'description']);
//dd($sub_categories);
return view('agencydash', compact('sub_categories'));
Comments