I have two database tables Players and Units. Respectively I also have two classes in PHP that look pretty identically in the base.
class Player {
private $id;
private $name;
// a bunch of other properties
public function __construct($id){
// fetch info from database with $id and populate properties
}
}
class Unit {
private $id;
private $name;
// a bunch of other properties
public function __construct($id){
// fetch info from database with $id and populate properties
}
}
But one player can have multiple units, so I implemented the method loadUnits() in the Player class
public function loadUnits(){
$units = array();
foreach($db->prepare('SELECT id FROM units WHERE owner = ?')->execute([$this->id])->fetchAll() as $unit){
$units[] = new Unit($unit['id']);
}
return $units;
}
The problem is that constructing Unit X number of times will make X number of calls to the database and this is really something I don't like. I would like to ask what are the good practices and how is this done in reality? Thanks!
SELECT id FROM units WHERE owner IN ('x', 'y', 'z')Player, no matter how many the units are. Did you mean X queries for X players?Unit's constructor there's also a call to the database to retrieve the unit's other stats