mpixelz
mpixelz

Reputation: 53

Laravel Relationship 3 Models

i have 3 models User, Campus, UserStatus. Structure is like this:

Campus
 - id
 - name
User
 - id
 - name
UserStatus
 - id
 - admission_date
 - current_status
 - user_id
 - campus_id

I would like to know how many users in a particular campus.. This is what i have done so far.
User.php

public function UserStatus()
    {
        return $this->hasOne('App\Models\UserStatus' , 'user_id');
    }

Campus.php

public function UserStatus()
    {
        return $this->hasMany('App\Models\UserStatus');
    }

UserStatus.php

public function User()
    {
        return $this->belongsTo('App\User', 'user_id');
    }
public function Campus()
    {
        return $this->belongsTo('App\Models\Campus', 'campus_id');
    }

what would be the relation for campus with user?

Upvotes: 0

Views: 65

Answers (3)

mpixelz
mpixelz

Reputation: 53

Instead i used a function:

public function User()
    {
        $users = \App\User::whereHas('UserStatus', function($q){
            $q->where('campus_id', $this->id);
        });
        return $users;
    }

worked for me.. I was hoping there was a better way of establishing a relationship instead. but for now its working. Thanks.

Upvotes: 0

Pablo Salazar
Pablo Salazar

Reputation: 957

You can use belongsToMany

I think that you have the same problem like this and he solve this using belongsToMany and "with" in the query with eloquent Stack overflow - Counting a many to many relationship

Upvotes: 0

bluestar0505
bluestar0505

Reputation: 701

You can use "has-many-through" relationship.

Please check following URL.

https://laravel.com/docs/5.8/eloquent-relationships#has-many-through

Upvotes: 1

Related Questions