我试着用Codeigniter的原则。
我在db中有两个表,作者和书籍。
Authors表有id、name和lastname字段。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;
}
}提前感谢
发布于 2016-11-30 16:39:31
我给你一个使用queryBuilder的select查询模型。试着执行它。
$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();如果你遇到任何问题,请告诉我
建议-尝试自己编写代码。如果您遇到问题,请尝试调试。如果你不能,那么无论你尝试过什么,都只需要寻求帮助。
发布于 2017-06-08 10:07:13
您有一个实体类Author和Book。所以你可以使用下面的代码。您可以根据需要进行修改。
$authors = $em->getRepository("Author")->findAll();现在,您可以通过调用getBooks()来获取perticular author的书籍,例如:
$authors = $em->getRepository("Author")->findAll();//$em is entity manager
if (count($authors)):
foreach ($authors as $author):
$books= $author->getBooks(); //all books of current author
endforeach;
endif;建议:你应该在你的实体中定义命名空间。
https://stackoverflow.com/questions/40799720
复制相似问题