Laravel Eloquent - Get all records of child relation model - laravel

My data model is this:
Users > Offices > Organization
This is my model
class Organization extends Model {
protected $table = 'organizations';
public function offices()
{
return $this->hasMany('App\Models\Office');
}
public function users()
{
return $this->offices()->users();
}
....
So.. I want to get all users from an organization (of all the offices).
But I don't know how to do something like
$this->offices()->users();
(Avoiding user a manual collection or map to do that)
Thanks!

So, you have organization ID. You can load all users by using whereHas():
$users = User::whereHas('office', function ($q) use ($organizationId) {
$q->where('organization_id', $organizationId);
})
->get();
Make sure office() relationship is defined correctly in User model:
public function office()
{
return $this->belongsTo('App\Office');
}
Alternatively, you could define hasManyThrough() relationship:
public function users()
{
return $this->hasManyThrough('App\Office', 'App\User');
}
And use it:
$organization->users()

Related

Laravel Eloquent: whereHas on relationship involving multiple tables

I am working on a Laravel project. I am using Eloquent to query data from the database.
I have the following models
Donation.php
class Donation extends Model
{
public function donator()
{
return $this->belongsTo(User::class);
}
}
User.php
class User extends Model
{
public function charities()
{
return $this->belongsToMany(Charity::class);
}
}
Charity.php
class Charity extends Model
{
public function donators()
{
return $this->belongsToMany(User::class);
}
}
I am writing a query on Donation model class and I am trying to query something like this. The query is just abstraction.
Donation::whereHas('donator.charities', function($query) {
$query->whereIn('charities.id', [ 1,2,3,4 ])
})
As you can see in the whereHas, I am applying the where clause on charities of donator. Is it possible to do that? How can I do that?
I hope this would be the answer of your question.
Donation::whereHas('donator',function($query){
$query->whereHas('charities',function($query){
$query->whereIn('id',[1,2,3,4]);
})
})->get();

How I can make the same SQL query whith the halp of Eloqument ORM methods and models

I have followng database:
And database diagramm is on next picture. Simply speaking, Users have many shops, Shops have many products etc.
In need to select all products from all shops of particular user. In my Controller it's look like so:
But it's does't work (
Instade of this I try to write direct SQL
I just need to make following request by Eloqument methods
SELECT * FROM tmp.products
WHERE tmp.products.shop_id IN
(SELECT id FROM shops where user_id = 1);
with dynamics parametrs of course.
You could get all products by using whereHas filter like
$products = Product::whereHas('shop.user', function ($query) use($request) {
$query->where('id', '=', $request->user()->id);
})->get();
I assume you have defined proper mappings in your models like
class Product extends Model {
public function shop() {
return $this->belongsTo('Shop', 'shop_id');
}
}
class Shop extends Model {
public function user() {
return $this->belongsTo('User', 'user_id');
}
public function products() {
return $this->hasMany('Product', 'shop_id');
}
}
class User extends Model {
public function shops() {
return $this->hasMany('Shop', 'user_id');
}
}

Laravel 5 - Eloquent: easier way to filter a many to many relationship

I have a many to many relationship between Lists and Users.
This is the List Model:
class ListModel extends Model
{
protected $table = "lists";
public function users()
{
return $this->belongsToMany('App\Models\User', 'list_user', 'list_id', 'user_id')->withTimestamps();
}
}
This is the User model:
class User extends Authenticatable
{
public function lists()
{
return $this->hasMany('App\Models\ListModel');
}
}
In a list page, I need to get all the lists belonging to the logged user. The only solution I found is this one:
$user = \Auth::user()->id;
$all_lists = ListModel::whereHas('users', function ($query) use ($user) {
$query->where('user_id', $user);
})->active()->get();
is there any simpler way to achieve the same result?
Since current user is already loaded, you can use lazy eager loading to load lists for the user:
auth()->user()->load('lists');
Your lists() relationship is not defined correctly. The inverse of belongsToMany is still belongsToMany (hasMany's inverse is belongsTo):
class User extends Authenticatable
{
public function lists()
{
return $this->belongsToMany('App\Models\ListModel', 'list_user', 'user_id', 'list_id')->withTimestamps();
}
}
Then you can get the lists like this:
$user = \Auth::user();
$all_lists = $user->lists()->active()->get()

Laravel query multiple tables using eloquent

hi sorry bit of a newbie here but I am have three tables users, profiles, friends. they all have the user_id fields within them and I want fetch all of the fields in one statement using Eloquent and not DB::statement and doing the table joins.
How can I achieve this?
Try this
use the User class and the with method that laravel has to query model relationships
$user = User::with(['profile', 'friend'])->get();
Ensure your models has the correct relationships as follows:
app/models/User.php
public function friend () {
return $this->hasMany('Friend');
}
public function profile () {
return $this->hasOne('Profile');
}
app/models/Profile.php
public function user() {
return $this->belongsTo('User');
}
app/models/Friend.php
public function user() {
return $this->belongsTo('User');
}
use some thing like this:
You should define relations in your models with hasOne, hasMany.
class Review extends Eloquent {
public function relatedGallery()
{
$this->hasOne('Gallery', 'foreign_id', 'local_id');
}
}
class Gallery extends Eloquent {
public function relatedReviews()
{
$this->hasMany('Review', 'foreign_id', 'local_id');
}
}
$gallery = Gallery::with('relatedReviews')->find($id);
Will bring the object Gallery with
$gallery->id
gallery->name
...
$gallery->relatedReviews // array containing the related Review Objects

Laravel Eloquent Relationship Through Tables

I have the following database tables:
users
id
name
seasons
id
name
teams
id
name
standings
id
season_d
team_id
user_id
fixtures
id
season_id
home_team_id
away_team_id
My question is, how would I get which user a team belongs to for a certain fixture? For example I may want to do the following:
$fixture = Fixture::find(1);
echo $fixture->homeTeam->user->name;
My models look like this:
Fixture Model
class Fixture extends Eloquent{
public function season(){
return $this->belongsTo('Season');
}
public function homeTeam(){
return $this->belongsTo('Team', 'home_team_id');
}
public function awayTeam(){
return $this->belongsTo('Team', 'away_team_id');
}
}
Team Model
class Team extends Eloquent{
public function standings(){
return $this->hasMany('Standing');
}
public function seasons(){
return $this->belongsToMany('Season', 'Standings');
}
public function users(){
return $this->belongsToMany('User', 'Standings');
}
}
Season Model
class Season extends Eloquent{
public function standings(){
return $this->hasMany('Standing');
}
public function teams(){
return $this->belongsToMany('Team', 'Standings');
}
public function users(){
return $this->belongsToMany('User', 'Standings');
}
public function fixtures(){
return $this->hasMany('Fixture');
}
}
I think I need to add a user function to the Team model instead of the current users function that's there, but I can't figure out the correct way to do the relationship. A team will only have one user for any given season. Any help would be appreciated, thanks!
UPDATE
I have added the following relationships to the Fixture model, which allows me to get the user and team through the standings table:
public function homeTeamStanding(){
return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'home_team_id', 'team_id')->where('season_id', $this->season_id);
}
public function awayTeamStanding(){
return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'away_team_id', 'team_id')->where('season_id', $this->season_id);
}
The problem with this is that I can't use it with eager loading, so there's quite a lot of queries running, as when I try to eager load them $this->season_id is null. Surely there's a better way?
I replaced the above with joins instead so that I can eager load which results in a lot less queries!
public function homeTeamStanding(){
return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'home_team_id', 'team_id')
->join('fixtures', 'fixtures.season_id', '=', 'standings.season_id');
}
public function awayTeamStanding(){
return $this->belongsTo('App\Modules\Leagues\Models\Standing', 'away_team_id', 'team_id')
->join('fixtures', 'fixtures.season_id', '=', 'standings.season_id');
}

Resources