You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用未定义方法getArticulos引发BadMethodCallException错误求助

搞定Doctrine的BadMethodCallException:未定义方法'getArticulos'

嘿,这个错误我太熟了!本质就是Doctrine的EntityRepository不认你调用的getArticulos()方法,它只认三种类型的方法:

  • 自带的基础方法,比如find()、findAll()这些
  • 以findBy或findOneBy开头的动态查询方法(比如findByCategoria())
  • 你自己在Repository类里手动写的自定义方法

你的getArticulos()不属于以上任何一种,所以直接给你抛出异常了。下面给你两种解决办法,按需选就行:

办法一:在Repository里定义getArticulos()方法

假设你的实体是Articulo,先找到对应的ArticuloRepository类(一般在src/AppBundle/Repository/下面),然后添加这个自定义方法:

// src/AppBundle/Repository/ArticuloRepository.php
namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ArticuloRepository extends EntityRepository
{
    public function getArticulos()
    {
        // 这里写你需要的查询逻辑,比如获取所有文章,或者加过滤条件
        return $this->createQueryBuilder('a')
            // 可以加 ->where('a.estado = :estado') ->setParameter('estado', 1) 这类条件
            ->getQuery()
            ->getResult();
    }
}

别忘了给你的实体类关联这个Repository,不然Doctrine找不到:

// src/AppBundle/Entity/Articulo.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ArticuloRepository")
 */
class Articulo
{
    // 你的实体字段和其他方法
}

办法二:直接用Doctrine自带的findAll()

如果你只是想拿到所有的Articulo记录,完全没必要自己写方法,直接替换成findAll()就行:

// 在ProductosController的listarAction里修改这一行
$articulos = $this->getDoctrine()->getRepository('AppBundle:Articulo')->findAll();

顺便理一下错误发生的路径

这个异常是在EntityRepository的__call方法里抛出来的(对应vendor\doctrine\orm\lib\Doctrine\ORM\EntityRepository.php第226行),而调用这个方法的地方是你ProductosController的listarAction第24行,你可以去那里确认一下调用的代码是不是写错了方法名。

内容的提问来源于stack exchange,提问作者Xisco Sánchez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:09:22