Sorry for the title, I didn't know what else to put.
I am looking to pull all the information on a user in a single database query.
There are 4 tables:
user
- userid (PK)
services
- serviceid (PK)
languages
- langid (PK)
areas
- areaid (PK)
user_services
- user_services_id (PK)
- serviceid (FK)
- userid (FK)
user_languages
- user_lang_id (PK)
- langid (FK)
- userid (FK)
user_areas
- user_area_id (PK)
- areaid (FK)
- userid (FK)
Both user
and user_services
I can pull out fine together as they have one row each and are linked by the user.id.
The user_languages
and user_areas
table are one to many tables and look similar to:
user_lang_id | userid | langid
1 | 5 | 2
2 | 5 | 6
3 | 5 | 18
user_area_id | userid | areaid
1 | 5 | 15
2 | 5 | 4
3 | 5 | 13
What I want the array to look like is this:
Array
(
[id] => 5
[firstname] => lethal
[surname] => Mango
[gender] => male
...
[langid] => 2
[langid] =&g开发者_Go百科t; 6
[langid] => 18
...
[areaid] => London
[areaid] => Birmingham
[areaid] => Manchester
}
I have tried a combination SQL JOINs but that didn't seem to get very far. My last resort was to do 3 seperate queries and join the PHP arrays together at the end (super messy).
Thanks :)
We can help you more if you provide us with the structure of the tables, but you can do it with JOINs as long as all your tables share a foreign key to one another. It doesn't have to be the same key field (such as user_id), but that does make it more straightforward. With joins, you should have something like this:
select * from user
left join user_services on user_services.id = user.id
left join user_languages on user.id = user_languages.id
left join user_areas on user.id = user_areas.id
This will give you a virtual table that has all of the columns needed. You can then create an array from these columns with the data you need with something like this:
foreach($query_result as $field => $value) {
$user[$field] = $value;
}
*Note - Code samples are untested and only for sample purposes.
精彩评论