0

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?

mpixelz
  • 53
  • 1
  • 7
  • I know this doesn't really answer your question, but just curious: why have both User and UserStatus table? It looks like they all relate to a single user so couldn't it all go on the User table? – Brian Thompson Nov 11 '19 at 22:08
  • 1
    Im just showing relevant information here.. These tables have so much other columns in them.. I had to separate them due to some other relationships. in short it was kind of a requirement at the time. – mpixelz Nov 11 '19 at 22:11
  • So to clarify, User belongs to one Campus, and Campus has many Users correct? – Brian Thompson Nov 11 '19 at 22:14
  • yes thats correct – mpixelz Nov 11 '19 at 22:15

3 Answers3

1

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

Please check following URL.

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

kbin0505
  • 170
  • 1
  • 11
  • The document suggests ` countries id - integer name - string users id - integer country_id - integer name - string posts id - integer user_id - integer title - string ` where as i dont have relation column on my second model.. both keys are in one model – mpixelz Nov 11 '19 at 22:30
  • you can use only UserStatus::where('campus_id', $particular_campus_id)->count(); – kbin0505 Nov 11 '19 at 22:47
  • so there is no way to access $campus->user->count();? – mpixelz Nov 11 '19 at 22:54
  • I think to it is no need to use relationship. Why? UserStatus has user_id and campus_id both. So you can get count in that table. – kbin0505 Nov 11 '19 at 22:55
0

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

Pablo Salazar
  • 800
  • 10
  • 17
0

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.

mpixelz
  • 53
  • 1
  • 7