Supposing I want to have users who have no posts in an application, usually with sql I write something like this:
SELECT p.* FROM users u
LEFT JOIN posts p on u.user_id=p.user_id;
Now I'm wondering, if I wanted to take all posts for single user from application, including also those who don't have any posts, it would go something like this:
class User {
private int $id;
public function __construct(int $id)
{
$this->id = $id;
}
public function posts() : Generator
{
$sql = 'SELECT post_id FROM posts WHERE user_id=' . $this->id;
foreach(Db::fetchObject($sql) as $post){
if(!$post->post_id) continue; // This assure inner join without this is left join?
yeld new Post($post->post_id);
};
}
}
Now the if on the foreach ensures the inner join because it eliminates empty results and basically if one loops all users, it won't get users who don't have any posts. But if I wanted to have users who don't have posts, would I just remove the if in the foreach loop and expect an exception that would then return null or 0 as a result? Or do something else need to be done?
I know you have to bind the fecthObject but I've simplified the code a bit, since I'm interested in understanding how to convert queries into objects and maintain relationships, there's a book about that that explains how to bind between data domain to one object?