With a query that complex it would probably be more performant to just use the raw sql. But I'm no expert
When not to use eloquent
For exporting data for reports in my web app from a database with about 25 tables, I need to run this query with many joins. The raw mysql query has about 20 left joins. And in the select I'm using many GROUP_CONCAT(DISTINCT ) statements like the one below, to put comma separated lists of items in one cell (to be used in the excel export file):
SELECT
GROUP_CONCAT(DISTINCT categories.`category` ORDER BY categories.`category` SEPARATOR ', ') AS `categories`,
GROUP_CONCAT(DISTINCT countries.`country` ORDER BY countries.`country` SEPARATOR ', ') AS `countries`,
// etc
FROM projects
LEFT JOIN tags
... etc
Trying to get this query working in eloquent, my code is becoming very long and messy. Like:
$rows = array();
foreach($projects as $project){
$row = array();
// Title
$row[] = $project->title;
// ... more
// project many to many categories. Have to loop through relation
$categories = array();
foreach($project->categories as $category) {
$category_name = $category->category;
if(!in_array($category_name, $categories)){
array_push($categories, $category_name);
}
}
$row[] = implode(';', $categories);
// .. more of the same
}
The complete code will probably be 100-200 lines long. The original mysql maybe 30-40 lines, depending on how you layout the sql.
So, should I just stick with raw mysql in this case, or am I doing something wrong with the eloquent methods above and could that be much more simplified?
Please or to participate in this conversation.