简体   繁体   中英

how to handle inner join and one to many relation with OOP?

Let's say I have an author and article tables. One article can have many authors. So it's a one to many relationship. I created an article class and an author class.

class author
{
    private $id;
    private $name;

    public function __construct($array)
    {
        foreach($array...
    }

    // getters...
    // setters...
}
class article
{
    private $id;
    private $title;
    private $content;

    private $author = array();

    public function __construct($array)
    {
        foreach($array...
    }

    // getters...
    // setters...

    public function setAuthor(author $author)
    {
        $this->author[] = $author;
    }
}

Notice setAuthor, a setter dependency injection. It needs an author object to keep the one to many relationship (one article, many authors).

I retrieve one article with its authors from the database.

$sql = $db->prepare("SELECT article.id AS id_article, title, content,
GROUP_CONCAT(author.id SEPARATOR ';') AS id_author,
GROUP_CONCAT(name SEPARATOR ';') AS name FROM article ar
INNER JOIN author au ON ar.id=au.article_id
WHERE article.id=:id GROUP BY article.id"); 

$sql->bindValue(':id', $id, PDO::PARAM_INT);

sql->execute();

$fromDb = $sql->fetch();

Now I have to build objects, right ?

$article['id'] = $fromDb['id_article'];
$article['title'] = $fromDb['title'];
$article['content'] = $fromDb['content'];

$id_author = explode(';', $fromDb['id_author']);
$name = explode(';', $fromDb['name']);

$newArticle = new article($article);

foreach($id_author as $key => $value)
{
   $author['id'] = $value;
   $author['name'] = $name[$key];

   $newArticle->setAuthor(new author($author));
}

I find the last part pretty heavy and not practical. I'm not sure it's the right way to do it. Same problem occurs with many to many relationship.

How to use objects once you get the datas from db in this particular case ?

You can use the PDO .

An example:

<?php

$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');

try {
    $results = $db->query(
          "SELECT *
          FROM articles ar
          INNER JOIN authors au ON ar.id=au.article_id"
    );
} catch (Exception $e) {
    echo "bad query";
    echo $e;
}

$items = $results->fetch(PDO::FETCH_ASSOC);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM