我刚刚开始使用 CakePHP 并遇到了一些问题。我有这个搜索功能,用于在 mysql 数据库(艺术家和 ArtistSurname)中搜索两个表,如下所示:
class ArtistsController extends AppController {
public function search ($search) {
if ($search){
$artists = $this->Artist->find('all', array('conditions' => array("surname like '%$search%' AND Artist.id = ArtistSurname.artist_id OR firstname like '%$search%' AND Artist.id = ArtistSurname.artist_id"), 'limit' => 400, 'fields' => array('Artist.firstname', 'ArtistSurname.surname', 'Artist.dbirth', 'Artist.id')));
if (!$artists){
throw new NotFoundException(__('No search result.'));
}
$result = array();
foreach ($artists as $artist) {
$fetchedArtist = array('value' => $artist['ArtistSurname']['surname'] . " " . $artist['Artist']['firstname'], 'year' => $artist['Artist']['dbirth'], 'id' => $artist['Artist']['id']);
array_push($result, $fetchedArtist);
}
header("Content-Type: application/json");
echo json_encode($result);
$this->autoRender = false;
}
}
查询后,我将结果放入我的自动完成(typeahead.js)的新可读数组中,并将其作为 json 回显。只要查询找到名字就可以正常工作,但如果查询仅找到姓氏则不行。奇怪的是,我只有在找到名字时才从我的 GET 请求中收到 application/json,否则我会在 text/html 中得到正确的结果。为什么是这样?