2017-10-13 118 views
0

上下文:
我正在使用CakePHP 3.x,并且正在尝试构建带分页的ORM查询。我有表用户,主题和区域。用户可以有很多主题,但只有一个区域。这是DB模式:CakePHP 3.x查询许多带分页的Table对象

CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY, 
email VARCHAR(255) NOT NULL, 
password VARCHAR(255) NOT NULL, 
); 
CREATE TABLE topics (
id INT AUTO_INCREMENT PRIMARY KEY, 
user_id INT NOT NULL, 
name VARCHAR(255), 
description TEXT, 
FOREIGN KEY user_key (user_id) REFERENCES users(id) 
); 
CREATE TABLE areas (
id INT AUTO_INCREMENT PRIMARY KEY, 
title VARCHAR(255), 
UNIQUE KEY (title) 
); 
CREATE TABLE users_areas (
user_id INT NOT NULL, 
area_id INT NOT NULL, 
PRIMARY KEY (user_id, area_id), 
FOREIGN KEY area_key(area_id) REFERENCES areas(id), 
FOREIGN KEY user_key(user_id) REFERENCES users(id) 
); 

我需要什么
我需要给出一个区域过滤的所有主题。
我想了下:

//1. get the area from the url (OK) 
$area = $this->request->getQuery('area'); 

//2. Get the area from db to get the id 
$myarea = $this->Areas->find()->where(['title' => $area])->first(); 

//3. Get all the users related to the area given 
$users = $this->Users->find()->matching('Areas', function ($q){ 
      return $q->where(['Areas.id' => $myarea->id]); 
      }); 

//4. Get the Topics and Paginate 
$topics = $this->paginate($this->Topics->find('all')->innerJoinWith('Users', function ($q){ 
      return $q->where(['User.id' => $myarea->id]); 
     })); 

//5. Set the topics (OK) 
$this->set(compact('topics')); 
$this->set('_serialize', ['topics']); 

我得到吨的错误,我不知道如何才能正确地构建查询。

+0

您可以张贴什么错误,你让他们中的至少一种? – KaffineAddict

回答

0

乍一看,有至少一个错误:

$myarea是匿名函数里面看不到的。

如果你想在lambda函数中使用$myarea,你应该从父范围继承这个变量:use($var)

http://php.net/manual/en/functions.anonymous.php例如#3

$users = $this->Users->find()->matching('Areas', function ($q) use ($myarea) { 
    return $q->where(['Areas.id' => $myarea->id]); 
}); 


$topics = $this->paginate($this->Topics->find('all')->innerJoinWith('Users', function ($q){ 
     return $q->where(['User.id' => $myarea->id]); 
}));