Consider the following READ and WRITE queries:
Read
// Retrieves a person (and their active game score if they have one)
$sql = "SELECT CONCAT(people.first_name,' ',people.last_name) as 'name',
people.uniform as 'people.uniform',
games.score as 'games.score'
FROM my_people as people
LEFT JOIN my_games as games ON(games.person_id = people.id AND games.active = 1)
WHERE people.id = :id";
$results = DB::select(DB::raw($sql),array("id"=>$id));
Write
// Saves a person
$person = new People;
$person->data = array('first_name'=>$input['first_name'],
'last_name'=>$input['last_name'],
'uniform'=>$input['uniform']);
$personID = $person->save();
// Save the game score
$game = new Games;
$game->data = array('person_id'=>$personID,
'active'=>$input['active'],
'score'=>$input['score']);
$game->save();
- I put every write (INSERT/UPDATE) operation into my own centralized repository classes and call them using class->methods as shown above.
- I may decide to put some of the read queries into repository classes if I find myself using a query over and over (DRY). I have to be careful of this, because I tend to go back and adjust the read query slightly to get more or less data out in specific areas of my application.
- Many of my read queries are dynamic queries (coming from datagrids that are filterable and sortable).
- The read queries will commonly have complex things like SUMs, COUNTs, ORDERing, GROUPing, COMPOSITE keys, etc.
Since my reads are so diverse, why would I need to further abstract them into Laravel's Eloquent ORM (or any ORM), especially since I'm using PDO (which has 12 different database drivers)? The only advantage I can see at the moment is if I wanted to rename a database field then that would be easier to do using the ORM. I'm not willing to pay the price in greater abstraction/obscurity for that though.