0
後の私は、この検索文を作成し、それが期待通りに動作しないいくつかの研究:CakePHPの3.xのサブ選択
public $virtualFields = array(
'count' => "SELECT COUNT(plans_trainings.id) FROM plans_trainings, trainings, projects WHERE plans_trainings.training_id = trainings.id AND projects.location_id = locations.id AND plans_trainings.project_id = projects.id"
);
public function trainingsPerLocationChartData(){
$this->loadModel('Locations');
$locationsDiagramData = $this->Locations->find('all', array(
'fields' => array(
'locations.id',
'locations.description',
'locations.count' /* virtuel field */
)
));
文は次のようになります。
'sql' => 'SELECT locations.id AS `locations__id`, locations.description AS `locations__description`, locations.count AS `locations__count` FROM locations Locations'
仮想フィールドがまったく認識されません。 どうすれば間違っていますか?
UPDATE: 私はこのようにそれを呼び出す必要があることが分かった:
'count' => "(SELECT COUNT(plans_trainings.id) FROM plans_trainings, trainings, projects WHERE plans_trainings.training_id = trainings.id AND projects.location_id = locations.id AND plans_trainings.project_id = projects.id) AS `counter`"
私は選択の周り)(追加しました。
$locationsDiagramData = $this->Locations->find('all')
->select(['locations.id', 'locations.description', $this->virtualFields['count']]);
しかし、私はまだ間違ったSQL構文を取得:
SELECT locations.id AS `locations__id`, locations.description AS `locations__description`, (SELECT COUNT(plans_trainings.id) FROM plans_trainings, trainings, projects WHERE plans_trainings.training_id = trainings.id AND projects.location_id = locations.id AND plans_trainings.project_id = projects.id) AS `counter` AS (SELECT COUNT(plans_trainings__id) FROM plans_trainings, trainings, projects WHERE plans_trainings FROM locations Locations
"最後" の問題は、AS counter
後にのみ、この部分に思える:
AS(SELECT COUNT(plans_trainings__id)FROM plans_trainings、training、 プロジェクト計画通りの場所
これは、ステートメントが壊れたものです! これを解決する方法はありますか? phpmyadminでステートメントを実行し、この部分を削除した場合、ステートメントは正常に動作し、正しい結果が得られます!
UPDATE 2: これは平野文です:
select
locations.id,
locations.description,
(
select
count(plans_trainings.id)
from
plans_trainings,
trainings,
projects
where
plans_trainings.training_id = trainings.id
and projects.location_id = locations.id
and plans_trainings.project_id = projects.id
) as 'Anzahl'
from
locations;
でこれを試してみてください**](http://book.cakephp.org/3.0/en/orm/query-builder.html#subqueries)を開き、[** 'select()' **](http:// book)に渡してください。 cakephp.org/3.0/en/orm/query-builder.html#selecting-data)。 – ndm