简体   繁体   中英

laravel many-to-many relationship return non related data

I have a relationship in my applications that is basically,

Many Organisations can have many Users, and many Users can have many Organisations.

So a many-to-many relationship, the organisation model relationship looks like this,

public function users() {
        return $this->belongsToMany('User')
                    ->where('admin', '>', 0)
                    ->orWhere('basic', '>', 0)
                    ->withPivot([
                        'start_date'       =>    'start_date as start_date',
                        'admin'            =>    'admin as admin',
                        'manager'          =>    'manager as manager',
                        'finance'          =>    'finance as finance',
                        'basic'            =>    'basic as basic',
                        'notifications'    =>    'notifications as notify'
                    ])
                    ->withTimestamps();
    }

and my user model relationship to organisations looks like this,

public function organisations()
{
    return $this->belongsToMany('Organisation');
}

I am having a huge problem with this relationship however, when I access this through project ( a project has one organisation, that has many users), I get a full list of users rather than just the users of the organisation for that project.

Why would this be? I think it is to do with my where clauses in the Users() function in my organisation model?

I don't see the reason you use all this code! I would say, Just make it simple:

Organisation class

public function users() {
    return $this->belongsToMany('App\User');
}



User class

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM