Created
July 17, 2018 12:03
-
-
Save johannesnagl/89e02bcab2284f6ecd50397844e45985 to your computer and use it in GitHub Desktop.
CakePHP2 Postgres Lateral Join Hack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// … | |
CakePlugin::load('PostgresApp'); | |
// … |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// … | |
public $default = [ | |
// … | |
'datasource' => 'PostgresApp.Database/PostgresApp', | |
// … | |
]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// … | |
$posts = $this->find('all', [ | |
'fields' => [ | |
'Post.id', | |
'Post.title', | |
'"Comment"."field1" AS "Comment__field1", | |
'"Comment"."field2" AS "Comment_field2", | |
], | |
'joins' => [ | |
'type' => 'LEFT LATERAL', | |
'alias' => 'Comment', | |
'table' => '( | |
SELECT field1, field2 FROM comments WHERE post_id = "Post"."id" AND truthy_column = true | |
)', | |
], | |
]); | |
// … |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
App::uses('Postgres', 'Model/Datasource/Database'); | |
/** | |
* A Postgres driver to support our special "LEFT LATERAL" join case. | |
*/ | |
class PostgresApp extends \Postgres | |
{ | |
/** | |
* Renders a final SQL JOIN statement | |
* | |
* @param array $data The data to generate a join statement for. | |
* @return string | |
*/ | |
public function renderJoinStatement($data) { | |
if (strtoupper($data['type']) === 'LEFT LATERAL') { | |
return "LEFT JOIN LATERAL {$data['table']} {$data['alias']} ON (TRUE)"; | |
} | |
return parent::renderJoinStatement($data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment