我正在使用带有CakePHP 3.8的friendsOfCake/search插件。
我有两个桌子喜欢这个
株
Name | user_id
-----------------
Strain1 | 1
Strain2 | 1
Strain3 | 2
用户
Name | id
-----------------
Peter | 1
Max | 2
其中Strains.user_id
是指Users
表中的id
列。
我想创建一个搜索掩码,我可以在其中搜索用户名,结果应该是该用户创建的菌株列表。 例如,如果我输入"Peter",结果应该是"Strain1"和"Strain2"。
根据 https://github.com/FriendsOfCake/search/tree/master/docs#options 我编写了以下代码
应变表.php
public function initialize(array $config)
{
parent::initialize($config);
$this->addBehavior('Search.Search');
$this->searchManager()
->value ('user_id')
->like ('q', [ // q is the name of the input field in the view
'fields' => ['Users.name'],
'beforeProcess' => function (CakeORMQuery $query, array $args, SearchModelFilterBase $filter) {
$query->contain('Users');
},
]);
...
}
菌株控制器.php
public function index()
{
$query = $this->Strains
->find ('search', ['search' => $this->request->getQueryParams()]);
debug($query);
$this->set('strains', $this->paginate($query));
}
我收到错误消息错误:SQLSTATE[42S22]:找不到列:1054 "where 子句"中的未知列"Strains.q">
创建的 SQL-Query 就是这个SELECT Strains.name AS `Strains__name`, Strains.user_id AS `Strains__user_id`, Users.id AS `Users__id`, Users.name AS `Users__name` FROM strains Strains INNER JOIN users Users ON Users.id = (Strains.user_id) WHERE Strains.q like :c0
其中 c0 是 q 的值。
我很高兴得到任何形式的帮助。
最后我找到了解决方案:必须使用field
(而不是fields
(将输入查询q
映射到Users.name
列,并且fields
prob 用于指定外键。
$this->searchManager()
->value ('user_id')
->like ('q', [ // q is the name of the input field in the view
'field' => ['Users.name']
'fields' => ['user_id'],
'beforeProcess' => function (CakeORMQuery $query, array $args, SearchModelFilterBase $filter) {
$query->contain('Users');
},
]);
$this->value('Users.email', [
'field' => 'Users.email',
'beforeProcess' => function (Query $query) {
return $query->contain(['Users']);
},
]);