Skip to content

Instantly share code, notes, and snippets.

@alexdd55
Last active February 25, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexdd55/642713bef9aa29b051cbc76c411b70b1 to your computer and use it in GitHub Desktop.
Save alexdd55/642713bef9aa29b051cbc76c411b70b1 to your computer and use it in GitHub Desktop.
cake model relations and joins on orm
/* SQL Statement */
DROP DATABASE IF EXISTS `moviestest`;
CREATE DATABASE IF NOT EXISTS `moviestest` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `moviestest`;
DROP TABLE IF EXISTS `categories`;
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `categories` (`id`, `name`) VALUES
(1, 'Fantasy'),
(2, 'Action'),
(3, 'Abenteuer');
DROP TABLE IF EXISTS `movies`;
CREATE TABLE IF NOT EXISTS `movies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `movies` (`id`, `name`) VALUES
(1, 'Lord of the Rings');
DROP TABLE IF EXISTS `movies_categories`;
CREATE TABLE IF NOT EXISTS `movies_categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`movie_id` int(11) NOT NULL DEFAULT 0,
`category_id` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `movies_categories` (`id`, `movie_id`, `category_id`) VALUES
(1, 1, 1),
(2, 1, 3);
*/
<?php
// TODO: Bake the models
// TODO: find all categories to a movie in MoviesController.php
/ * does not work. */
$this->Movies->Categories->find()->where(['Movies.id => 1])
/* SQL that gives the expected result:
SELECT
categories.id,
categories.name
FROM
categories
INNER JOIN movies_categories ON categories.id = movies_categories.category_id AND movies_categories.movie_id = 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment