简体   繁体   中英

Laravel 5 Eloquent multiple relationships with multiple wheres

I have 2 tables: Calendar and User . Calendar has a one to many relation to User and User has a relation with itself via parentID :

//model Calendar.php
    public function users()
    {
        return $this->belongsTo(User::class,'userID');
    }
//model User.php
    public function parent()
    {
        return $this->belongsTo(self::class,'parentID','id');
    }

I already select it like I want but I want to add:

where('users.parent.parentID',$userID)->orWhere('users.parent.parentID',$userID);

but I don't think it will work. I tried to join, but I don't know how. I've tried:

$calendar = calendar::with('users','users.parent')->get()->where('users.parent.parentID',$userID);

and

$calendar = calendar::with('users','users.parent')->get()->where('users.parentID',$userID);
Calendar::with('users')
        ->whereHas('users', function($query) use ($userID) {
        $query->where('parentID', $userID)->orWhereHas('parent', function($query) use ($userID) {
            $query->where('parentID', $userID);
        });
    })->get();

This will load you all users that have parentID equal $userID OR users which parent have the same condition. For loading relation you have to use with function, for filtering relation use callback inside it, for filtering relation owner use functions whereHas or orWhereHas .

Try

$calendar = Calendar::with('users')
                    ->with(['users.parent' => function($q) use ($userID){
                               $q->where('parentID',$userID);
                           }])
                    ->get();

More information about relationship eager-loading constraints here: http://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads

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