var*_*ius 5 php mysql cakephp cakephp-2.0
我是CakePHP的新手,我正在尝试为结果构建复杂的查询.这太痛苦了.也许some1可以帮助我.我正在使用蛋糕2.7
我有两个表有3个关系(多对多).Neighbourhood和Polygon.案例看起来像这Neighbourhood有很多Neighbourhoods,它也属于很多Neighbourhoods.也Neighbourhood有许多Polygons和Polygon属于mnay Neighbourhoods.
Neighbourhood表包含2个字段name和zip.我从用户那里得到的是zip code.
而现在我想要的是:我希望得到所有的东西Polygons,Neighbourhood而且它是Neighbours.哪里Neighbourhood.zip = defined by user.
我怎样才能做到这一点?我应该编写自定义查询或将proccess分成更小的步骤吗?我整天都在和这个人打架.
模型关系看起来像这样:
class Neighbourhood extends AppModel
{
var $hasAndBelongsToMany = array(
'Neighbourhoods' => array(
'className' => 'Neighbourhood',
'joinTable' => 'neighbourhoods_neighbours',
'foreignKey' => 'neighbourhood_id',
'associationForeignKey' => 'neighbour_id',
'unique' => false
),
'Polygon' => array(
'className' => 'Polygon',
'joinTable' => 'neighbourhoods_polygons',
'foreignKey' => 'neighbourhood_id',
'associationForeignKey' => 'polygon_id',
'unique' => false
),
);
}
class Polygon extends AppModel
{
var $hasAndBelongsToMany = array(
'Neighbours' => array(
'className' => 'Neighbourhood',
'joinTable' => 'neighbourhoods_polygons',
'foreignKey' => 'polygon_id',
'associationForeignKey' => 'neighbourhood_id',
'unique' => false,
)
);
}
Run Code Online (Sandbox Code Playgroud)
您需要在模型中启用可包含的行为,或者在应用程序模型中设置它后效果更好。
public $actsAs = array('Containable');
Run Code Online (Sandbox Code Playgroud)
然后开始建立你的查询,例如
$conditions = array(
'conditions' => array('id' => '123'),
'contain' => array(
'Neighbourhood'=>array(
'conditions' => array('Neighbourhood.id' => '123')
)
),
// or even joins
'joins' => array(
array(
'table' => $this->getTableName('default', 'neighbourhoods'),
'alias' => 'Neighbourhood',
'type' => 'RIGHT', // OR LEFT
'conditions' => array(
'Neighbourhood.id = Polygon.neighbourhood_id',
'Neighbourhood.deleted' => 0,
)
)
)
);
$polygons = $this->Polygon->find('all', $conditions);
Run Code Online (Sandbox Code Playgroud)
如果您认为这还不够(为了执行更复杂的查询),那么您需要构建查询语句。例如,从 Polygon 模型运行查询:
$dbo = $this->getDataSource();
$query = $dbo->buildStatement(
array(
'fields' => array(
'Polygon.name AS polygon_name', 'Polygon.size',
'Neighbourhood.name AS neighbourhood_name', 'Neighbourhood.lat',
'IF( Neighbourhood.created > DATE_SUB(NOW(), INTERVAL 1 DAY) , 1 , 0) AS new_neighbourhood'
),
'table' => $dbo->fullTableName($this),
'alias' => 'Polygon',
'limit' => null,
'offset' => null,
'joins' => array(
array(
'table' => $this->getTableName('default', 'neighbourhoods'),
'alias' => 'Neighbourhood',
'type' => 'LEFT',
'conditions' => array(
'Neighbourhood.id = Polygon.neighbourhood_id',
),
'order' => 'Neighbourhood.name ASC',
),
....
),
'conditions' => $conditions,
'group' => 'Polygon.name',
'order' => 'Polygon.name ASC',
),
$this
);
$polygons = $this->query($query);
Run Code Online (Sandbox Code Playgroud)
如果你认为这还不够,那么你必须像这样唱出奇妙的恩典。
$polygons = $this->query("Here your sql query");
debug($polygons);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
839 次 |
| 最近记录: |