简体   繁体   English

如何处理内部连接和与 OOP 的一对多关系?

[英]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.注意 setAuthor,一个 setter 依赖注入。 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 ?在这种特殊情况下,一旦从 db 获取数据,如何使用对象?

You can use the PDO .您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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