Skip to content

Instantly share code, notes, and snippets.

@heroicpixels
Created January 10, 2014 15:26
Show Gist options
  • Select an option

  • Save heroicpixels/8356338 to your computer and use it in GitHub Desktop.

Select an option

Save heroicpixels/8356338 to your computer and use it in GitHub Desktop.
Demonstrating how to user Heroicpixels/Filterable with Eloquent joins and eager loading
CREATE TABLE IF NOT EXISTS `cats` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
INSERT INTO `cats` (`id`, `name`) VALUES
(1, 'Category One'),
(2, 'Category Two');
CREATE TABLE IF NOT EXISTS `cat_object` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cat_id` int(11) NOT NULL,
`object_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
INSERT INTO `cat_object` (`id`, `cat_id`, `object_id`) VALUES
(1, 1, 1),
(2, 2, 1);
CREATE TABLE IF NOT EXISTS `objects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`color` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`shape` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`size` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`total` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
INSERT INTO `objects` (`id`, `name`, `color`, `shape`, `size`, `total`) VALUES
(1, 'Object 1', 'red', 'square', 'l', 150),
(2, 'Object 2', 'blue', 'square', 's', 2000),
(3, 'Object 3', 'green', 'circle', 'm', 575),
(4, 'Object 4', 'yellow', 'triangle', 'xl', 15),
(5, 'Object 5', 'red', 'triangle', 'l', 900),
(6, 'Object 6', 'red', 'triangle', 'l', 600);
class Object extends Heroicpixels\Filterable\Filterable {
public function categories()
{
return $this->belongsToMany('Cat');
}
}
class Cat extends Heroicpixels\Filterable\Filterable {
}
/**
* Join
*/
$columns = array('color' => 'objects.color',
'name' => 'objects.name',
'shape' => 'objects.shape',
'category' => 'cat_object.cat_id');
$objects = Object::join('cat_object', 'objects.id', '=', 'cat_object.object_id')
->filterColumns($columns)
->get()->toArray();
/**
* Eager load
*/
$columns = array('color' => 'objects.color',
'name' => 'objects.name',
'shape' => 'objects.shape');
$results = array();
$objects = Object::with(array('categories' => function($q) {
$columns = array('category' => 'cat_object.cat_id');
$q->filterColumns($columns);
}))->filterColumns($columns)->get()->toArray();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment