Anu*_*TBE 2 cakephp model cakephp-3.0
我正在模型中创建一个函数来查找所有相关服务.
功能 ServiceCategory.php
class ServiceCategory extends Entity
{
public function relatedServices($id)
{
return $this->find('all', [
'conditions' => [
'where' => [
'id !=' => $id
],
'limit' => 5
]
]);
}
}
Run Code Online (Sandbox Code Playgroud)
并且呼唤 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']);
}
Run Code Online (Sandbox Code Playgroud)
但它给出了 Unknown method 'relatedServices'
我在做什么事情有什么不对吗?
在问题中:
class ServiceCategory扩展了Entity
这是一个实体类
$ relatedServices = $ this-> ServiceCategories-> relatedServices($ id);
这是对表对象进行调用,表对象和实体不相互继承,该方法对表类不可用.
直接的解决方案是将代码移动到表类:
// 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
]
]);
}
Run Code Online (Sandbox Code Playgroud)
虽然可以说是正确/更好的方法是实现一个查找程序:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
$relatedServices = $this->ServiceCategories->find(
'relatedServices',
['id' => $id]
);
Run Code Online (Sandbox Code Playgroud)