【问题标题】:Symfony - findOneOrFail returns array messageSymfony - findOneOrFail 返回数组消息
【发布时间】:2021-07-04 07:48:04
【问题描述】:

在我的 Symfony 服务中,我想添加一些小的编辑,所以我决定最好在课堂上进行。

在我的控制器中,我从我的请求中获取 storyId(它不是表 ID,它是具有不同字符的字符串),例如:

 $story = json_decode($request->getContent(), true);
 $storyId = $story['storyId'];

 $freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
 $story->freeStoryName($freeStoryName);

 return $this->json(["message" => "SUCCESS"]);

在我的实体类中,我处理它的方式如下:

public function freeStoryName(Story $story): Story
{
    $this->setPreviousStoryName($story->getStoryName());
    $story->setStoryName(null);
}

我收到错误消息:

调用数组上的成员函数freeStoryName()

我知道消息的含义但不明白?这是findOne() 方法.. 另一个问题是,我是否需要像在服务中那样在 Entity 类中使​​用 flush() 方法?

【问题讨论】:

  • findOneOrFail 方法从何而来?我可能错过了它,但它看起来不像是标准 Symfony 或 Doctrine 代码的一部分。
  • 它在 AbstractRepository 上。它包含 FindOneBy() 方法,所以应该没问题。 :) 我也试过 FindOneBy,同样的事情。 @FrancescoAbeni

标签: php symfony doctrine-orm entity symfony4


【解决方案1】:

您在 $story 上使用 freeStoryName,它是一个数组 (json_decode($request->getContent(), true);)

你需要用你的方法来处理你的结果:

 $story = json_decode($request->getContent(), true);
 $storyId = $story['storyId'];

 $freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
 $freeStoryName->freeStoryName($freeStoryName);

 return $this->json(["message" => "SUCCESS"]);

如果您觉得这样做有点奇怪,您可以将方法更改为:

public function freeStoryName()
{
    $this->setPreviousStoryName($this->getStoryName());
    $this->setStoryName(null);
}

并使用它:

$freeStoryName->freeStoryName();

【讨论】:

    猜你喜欢
    • 2016-09-24
    • 1970-01-01
    • 2019-01-07
    • 2019-08-07
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多