【问题标题】:CakePHP 3 : Unknown methodCakePHP 3:未知方法
【发布时间】:2016-06-26 08:34:34
【问题描述】:

我正在模型中创建一个函数来查找所有相关服务。

ServiceCategory.php中的函数

class ServiceCategory extends Entity
{

    public function relatedServices($id)
    {
        return $this->find('all', [
          'conditions' => [
            'where' => [
              'id !=' => $id
            ],
            'limit' => 5
          ]
        ]);
    }
}

并致电ServiceCategoriesController.php

public function view($id = null)
    {
        $serviceCategory = $this->ServiceCategories->get($id, [
            'contain' => ['Services']
        ]);

        $relatedServices = $this->ServiceCategories->relatedServices($id);

        $this->set('serviceCategory', $serviceCategory);
        $this->set('relatedServices', $relatedServices);
        $this->set('_serialize', ['serviceCategory']);
    }

但它给了Unknown method 'relatedServices'

我做错了什么吗?

【问题讨论】:

    标签: cakephp model cakephp-3.0


    【解决方案1】:

    代码在错误的类中

    在问题中:

    类 ServiceCategory 扩展实体

    这是一个entity

    $relatedServices = $this->ServiceCategories->relatedServices($id);

    这是对table对象的调用,表对象和实体不相互继承,该方法对表类不可用。

    将代码移到表类中

    直接的解决方法是将代码移到表类中:

    // src/Model/Table/ServiceCategoriesTable.php
    namespace App\Model\Table;
    
    class ServiceCategoriesTable extends Table
    {
    
        public function relatedServices($id)
        {
            return $this->find('all', [
              'conditions' => [
                'where' => [
                  'id !=' => $id
                ],
                'limit' => 5
              ]
            ]);
        }
    

    虽然可以说是正确/更好的方法是实现一个查找器:

    // src/Model/Table/ServiceCategoriesTable.php
    namespace App\Model\Table;
    
    use Cake\ORM\Query;
    use \InvalidArgumentException;
    
    class ServiceCategoriesTable extends Table
    {
    
        public function findRelatedServices(Query $query, array $options)
        {
            if (!isset($options['id'])) {
                $message = sprintf('No id in options: %s', json_encode($options));
                throw new InvalidArgumentException($message);
            }
            
            $query->where(['id !=' => $options['id']);
    
            return $query;
        }
    

    它的调用方式与其他 find calls 完全相同:

    $relatedServices = $this->ServiceCategories->find(
        'relatedServices', 
        ['id' => $id]
    );
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多