php - 代码点火器学说

标签 php mysql codeigniter doctrine-orm

我尝试将学说与 Codeigniter 结合使用。

我在数据库中有两个表,作者和书籍。

作者表包含字段 ID、姓名和姓氏。 Books 表包含字段 id、title 和author_id。

我知道如何将数据写入表中,但我不知道如何获取该作者所写的所有作者和书籍的列表。有人可以帮我吗?

作者模型

<?php
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @Entity @Table(name="authors")
 **/
class Author
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $name;
    /** @Column(type="string") **/
    protected $lastname;

    /**
     * @OneToMany(targetEntity="Book", mappedBy="author")
     */

    private $books;

    public function __construct()
    {
        $this->books = new ArrayCollection();
    }

    public function setAuthor($name,$lastname)
    {
        $this->name = $name;
        $this->lastname = $lastname;
    }

    public function authorName()
    {
        return $this->name.' '.$this->lastname;
    }

    public function updateAuthor($name,$lastname)
    {
        $this->name = $name;
        $this->lastname = $lastname;
    }

    public function setFirstName($name)
    {
        $this->name = $name;
    }

    public function setLastName($lastname)
    {
        $this->lastname = $lastname;
    }

    public function getBooks()
    {
        return $this->books;
    }

}

书籍模型

<?php
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @Entity @Table(name="books")
 **/
class Book
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $title;

    /**
     * @ManyToOne(targetEntity="Author", inversedBy="books")
     * @oinColumn(name="author_id", referencedColumnName="id")
     */

    private $author;

    public function setTitle($title)
    {
        $this->title = $title;
    }

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

    public function getTitle()
    {
        return $this->title;
    }

    public function getAuthor()
    {
        return $this->author;
    }
}

提前致谢

最佳答案

我为您提供了一个使用 queryBuilder 进行选择查询的模型。尝试执行它。

    $query= $this->doctrine->em->createQueryBuilder();
    $query->select('bk.id book_id,au.id author_id');
    $query->add('from', 'Entities\Authors au');
    $query->Join('Entities\Book', 'bk', 'with', 'bk.author=au.id');
    $query_data =$query->getQuery();
    $data = $query_data->getResult();

您遇到任何问题请告诉我

建议 - 尝试自己编写代码。如果您遇到问题,请尝试调试。如果你不能,那么只寻求你尝试过的帮助。

关于php - 代码点火器学说,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40799720/

相关文章:

php - 记录唯一文章浏览次数的最有效方法是什么

PHP 同时中断和继续

php - CodeIgniter 事件记录,在 ->select() 函数中添加 IF 语句

Php:没有 "Cannot redeclare class"时如何解析 "previously declared"

mysql - mysql 中的运行平均值

php - 在 MySQL 表中使用字符串作为 ID 可以吗?

MySql : Convert Column data to row

php - 使用 PHP curl 发送 xml 请求

html - 在 codeigniter 中显示网站图标时出现问题。标题显示代码

php - 从下拉列表填充多个文本框 - CodeIgniter/PHP