Why don't you view some free videos on this, he covers basic relations:
Help with Query involving two tables
Hello, I am still very much a beginner. I am looking for help with some code I'm trying modify old code involving a query. Here's a rough breakdown of the situation:
There are two tables, HOUSEHOLD and INFO
HOUSEHOLD (contains 'id', 'inhabitant_id', 'house_id').
- some households have 'house_id' as NULL if they have never been painted
- 'inhabitant_id' is NULL if vacant
INFO (contains 'id', 'sex', 'color')
- stupidly, inhabitant sex and house color are both stored here as independent entries. If entry is for an inhabitant, 'color' is NULL. If entry is for a house, 'sex' is NULL
- furthermore, if a Household's 'house_id' was NULL in HOUSEHOLD, it does not have an entry in INFO.
- the 'id' corresponds to 'inhabitant_id' OR 'house_id' from the HOUSEHOLD table
I want to query all HOUSEHOLDs that have a male inhabitant, AND where the house_id is either NULL in HOUSEHOLD or 'color' = red in its corresponding INFO entry.
Here's the code:
$query = $query->select('HOUSEHOLD.*')
->join('INFO', 'INFO.id', '=', 'HOUSEHOLD.inhabitant_id')
->where('INFO.sex', 'male')
->whereNotNull('inhabitat_id')
->join('INFO as i', 'i.id', '=', 'HOUSEHOLD.house_id')
->where('i.color', '=', 'red');
return $query;
When I run this, it is only returning households with male inhabitants with homes that are red. But I also want it to return households with houses that are unpainted (house_id=NULL).
Again I am very much learning, and I'm trying to clean up someone else's old code. I am very much stuck. Any help would be greatly appreciated!
Please or to participate in this conversation.