Ad
SQL Select Data From Two Tables, One Row -> Multiple Rows
I have the following two tables:
customers: | phones:
--------------------------------------
id | id
name | owner (FK_CUSTOMERS)
address | number
I load a html table in laravel blade to show all the customers and I want a table cell with the phones saved for each customer.
So one customer may have no phones, just one or multiple phones. I need to retrieve each customer with their phones in one row, or there is a better way to do this?
If I do something like this results one row per phone with duplicate data:
$customers = DB::table('customers')
->join("phones","customers.id", "=", "phones.owner")
->where("phones.group",1)
->select(
'customers.id',
'customers.name',
'customers.fiscalNumber',
'customers.disscount',
'customers.billAddress',
'customers.tax',
'phones.number'
)
->get();
I want this:
id | name | address | phones
5 | Michael | fake address 123 | 666777888,111222333,444555666
I have tried several things but nothings works. Thanks
Ad
Answer
You should group your customers by id, and use group_concat to extract all phone numbers as a comma separated string. It should look something like this:
$customers = DB::table('customers')
->join("phones","customers.id", "=", "phones.owner")
->where("phones.group",1)
->select(
'customers.id',
'customers.name',
'customers.fiscalNumber',
'customers.disscount',
'customers.billAddress',
'customers.tax',
DB::raw('group_concat(phones.number) as number')
)
->groupBy('customers.id')
->get();
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad