我使用的是一个简单的搜索功能,但问题是我通过findByTitle硬编码控制器中的类别标题值,然后将其传递给搜索功能。
类别与Post实体有一个OneToMany / ManyToOne关系。
尝试过以下操作但遇到以下错误:Error: Call to a member function getTitle() on a non-object
$em = $this->getDoctrine()->getManager();
$query = $this->get('search');
$category = $em->getRepository('AcmeDemoBundle:Category')
->findAll();
$categoryTitle = $em->getRepository('AcmeDemoBundle:Category')
->findByTitle($category->getTitle());
$posts = $query->search($categoryTitle);
如何动态设置此值,以便我不必手动传入此内容?
控制器
/**
* Search action
*
* @return array
*
* @Route("/search", name="job1_search")
* @Template("AcmeDemoBundle:Job1:search.html.twig")
*/
public function searchAction()
{
// Search code: calling from the service Search
$em = $this->getDoctrine()->getManager();
$query = $this->get('search');
$categoryTitle = $em->getRepository('AcmeDemoBundle:Category')
->findByTitle('job1');
$posts = $query->search($categoryTitle);
return array(
'query' => $query,
'posts' => $posts['results'],
);
}
搜索服务
public function search($categoryTitle)
{
$results = null;
$query = $this->request->query->get('q');
if (!empty($query)) {
$em = $this->doctrine->getManager();
$results = $em->createQueryBuilder()
->from('AcmeDemoBundle:Post', 'post')
->select('post')
->where('post.category = :category')
->setParameter('category', $categoryTitle)
->andWhere('post.title LIKE :search')
->addOrderBy('post.created', 'DESC')
->setParameter('search', "%${query}%")
->getQuery()
->getResult();
}
return array(
'query' => $query,
'results' => $results,
);
}
答案 0 :(得分:0)
findAll()
方法无论您是否持有一个或多个实体
$category = $em->getRepository('AcmeDemoBundle:Category')
->findAll();
这意味着在以下几行
$categoryTitle = $em->getRepository('AcmeDemoBundle:Category')
->findByTitle($category->getTitle())
你必须更改$category->getTitle()
,这是因为你在数组本身上调用方法而不是它包含的实体。
如果不确切地知道你想要做什么(使用一个或多个类别,如何选择,等等......),很难提供更多细节。
答案 1 :(得分:0)
好的,让我们从头开始:
$em = $this->getDoctrine()->getManager();
$query = $this->get('search');
// This will give an ArrayCollection of all AcmeDemoBundle:Category that you have
$category = $em->getRepository('AcmeDemoBundle:Category')
->findAll();
// In here $category is an array, so you cannot get it's title
// Also if you would have an actual entity set as $category - the $categorytitle would
// still be a AcmeDemoBundle:Category entity object, not a title string
$categoryTitle = $em->getRepository('AcmeDemoBundle:Category')
->findByTitle($category->getTitle());
$posts = $query->search($categoryTitle);
你有一个搜索查询字符串,所以我会选择:
// This will contain the entity object
$category = $em->getRepository('AcmeDemoBundle:Category')->findByTitle($query);
要获得标题:
$categoryTitle = $category->getTitle();