-
-
Save atrauzzi/6674488eb4fbd7a45671 to your computer and use it in GitHub Desktop.
Laravel Eloquent - Getting collections through nested relations.
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 | |
class Application extends Eloquent { | |
protected $table = 'applications'; | |
public function pushMessages() { | |
return $this->hasMany('PushMessage'); | |
} | |
} |
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
# 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 |
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 | |
class PushMessage extends Eloquent { | |
/** | |
* The database table used by the model. | |
* | |
* @var string | |
*/ | |
protected $table = 'push_messages'; | |
public function application() { | |
return $this->belongsTo('application'); | |
} | |
} |
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
$graph = User::with(array('Applications', 'Applications.PushMessages')) | |
->where("users.id", "=", Auth::user()->id) | |
->get() | |
; | |
$pushMessages = $graph->applications->pushMessages; |
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 | |
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