从实体调用存储库方法

编程入门 行业动态 更新时间:2024-10-22 21:34:32
本文介绍了从实体调用存储库方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在实体上调用存储库方法? 我的意思是这样的

Is it possible to call repository method on entity? I mean something like this

$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId)); $category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86)); $article->addArticleToCategory($category);

其中addArticleToCategory是存储库中的方法(只是示例代码)

Where addArticleToCategory is method in repository (just an example code)

public function addArticleToCategory($category){ $categoryArticles = new CategoryArticles(); $categoryArticles->setArticle(!!/** This is where I want to have my variable $article from this method call **/!!); $categoryArticles->setCategory($category); $this->getEntityManager()->persist($categoryArticles); $this->getEntityManager()->flush(); }

最佳方法是什么?

我还想知道将自定义set / create方法放入存储库中是一种好习惯吗?

Also I want to know is it a good practice to put custom set/create methods in repository?

推荐答案

根据定义,您不能从实体对象调用存储库类的方法...这是基本的面向对象编程。

By definition you can't call a method of your repository class from an entity object... This is basic object-oriented programming.

我认为您应该在 Category 实体中创建 addArticle 函数,如下所示:

I think you should create addArticle function in the Category entity, something like this:

function addArticle($article) { $this->articles[] = $article; $article->setCategory($this); }

然后您做

$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId)); $category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86)); $category->addArticle($article); $em->persist($category); $em->flush();

如果级联配置正确,则可以使用

If the cascades are correctly configured, this will work

更多推荐

从实体调用存储库方法

本文发布于:2023-11-17 04:56:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608911.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!