Skip to content

Instantly share code, notes, and snippets.

@atrauzzi
Last active December 15, 2015 08:39
Show Gist options
  • Save atrauzzi/6674488eb4fbd7a45671 to your computer and use it in GitHub Desktop.
Save atrauzzi/6674488eb4fbd7a45671 to your computer and use it in GitHub Desktop.
Laravel Eloquent - Getting collections through nested relations.
<?php
class Application extends Eloquent {
protected $table = 'applications';
public function pushMessages() {
return $this->hasMany('PushMessage');
}
}
# This is generally speaking what I'm after. Eloquent may add the User table back in depending on how it builds things.
SELECT push_messages.*
FROM push_messages
LEFT JOIN applications ON push_messages.id = applications.id
LEFT JOIN application_users ON application_users.application_id = applications.id
WHERE
application_users.user_id = 1
<?php
class PushMessage extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'push_messages';
public function application() {
return $this->belongsTo('application');
}
}
$graph = User::with(array('Applications', 'Applications.PushMessages'))
->where("users.id", "=", Auth::user()->id)
->get()
;
$pushMessages = $graph->applications->pushMessages;
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
public function applications() {
return $this->belongsToMany('Application', 'application_users', 'user_id', 'application_id');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment