Skip to content

Instantly share code, notes, and snippets.

@armincifuentes
Last active August 29, 2015 14:23
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 armincifuentes/504f6dc20e486cb7b95f to your computer and use it in GitHub Desktop.
Save armincifuentes/504f6dc20e486cb7b95f to your computer and use it in GitHub Desktop.
Eloquent manyThroughMany()
<?php
/*
* manyTroughMany()
*
* Enables access to distant relations
* using many-to-many pivot tables.
*
* Proposed by @terion-name at Laravel.io Forums
* http://laravel.io/forum/03-04-2014-hasmanythrough-with-many-to-many
*
*/
public function manyThroughMany($related, $through, $firstKey, $secondKey, $pivotKey) {
$model = new $related;
$table = $model->getTable();
$throughModel = new $through;
$pivot = $throughModel->getTable();
return $model
->join($pivot, $pivot . '.' . $pivotKey, '=', $table . '.' . $secondKey)
->select($table . '.*')
->where($pivot . '.' . $firstKey, '=', $this->id);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment