How should relationships between tables be handled in PHP classes representing each table?
When representing tables in PHP classes, relationships between tables can be handled by creating methods within the classes to retrieve related data from other tables. This can be done by using foreign keys to establish relationships between tables and then using JOIN queries to fetch related data when needed.
class User {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function getPosts() {
$query = "SELECT * FROM posts WHERE user_id = :user_id";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':user_id', $this->id);
$stmt->execute();
return $stmt->fetchAll();
}
}
class Post {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function getUser() {
$query = "SELECT * FROM users WHERE id = :user_id";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':user_id', $this->user_id);
$stmt->execute();
return $stmt->fetch();
}
}
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$user = new User($db);
$user->id = 1;
$posts = $user->getPosts();
foreach ($posts as $post) {
$postObj = new Post($db);
$postObj->id = $post['id'];
$user = $postObj->getUser();
echo $user['username'] . ': ' . $post['content'] . '<br>';
}
Related questions
-
language barriers installation process PHP applications
-
PHP optimization unintended increments
-
PHP variables error messages