使用hasMany关系通过数据透视表获取数据

时间:2016-01-28 17:29:13

标签: laravel eloquent

您好我有这三种模式:

user.php的

<?php namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Kodeine\Acl\Traits\HasRole;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword, HasRole;

    /**
     * The database table used by the model.
     *
     * @var stringSS
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password', 'is_active'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    public function roles()
    {
        return $this->belongsToMany('App\Models\Role', 'role_user', 'user_id', 'role_id');
    }

    public function bankBranch()
    {
        return $this->belongsToMany('App\Models\BankBranch', 'bank_branches_users', 'user_id', 'branch_id');
    }

    public function permissions()
    {
        return $this->belongsToMany('App\Models\Permissions', 'permission_user', 'user_id', 'permission_id');
    }

}

Bank.php

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Bank extends Model {

    protected $table = 'bank_details';

    public function branches()
    {
        return $this->hasMany('App\Models\BankBranch', 'bank_id');
    }

    public function users()
    {
        return $this->hasManyThrough('App\Models\User', 'App\Models\BankBranch');
    }

}

BankBranch.php

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BankBranch extends Model {

    protected $table = 'bank_branches';

    public function bank()
    {
        return $this->belongsTo('App\Models\Bank', 'bank_id');
    }

    public function users()
    {
        return $this->hasMany('App\Models\User', 'bank_branches_users', 'branch_id', 'user_id');
    }

}

好的,现在在我的应用程序中,我有以下关系: 1.用户属于许多银行分行。 银行分行属于一家银行。 3. BankBranch有很多用户。

现在,当用户登录时,我希望他们只能看到与用户在同一银行分行内的其他用户。

在我的admin-&gt;用户页面上的含义我想要一个与登录用户在同一分支中的用户列表。

除非登录用户属于许多其他分支,否则它应该显示登录用户所属分支中的所有用户。

我很难在我雄辩的模型中代表这一点并通过我的控制器获取数据。

1 个答案:

答案 0 :(得分:2)

获取用户bankBranches ID:

$branchIds = Auth::user()->bankBranch()->get()->lists('id');

比gettting属于这个分支的所有用户:

$usersInBranches = BankBranch::whereIn('id',$branchedIds)->with('users')->get();

或:

$usersInBranches = User::whereHas('bankBranch', function($query) use ($branchIds) {
 $query->whereIn('id',$branchIds);
})->get();

编辑甚至更好:

$usersInBranches = User::whereHas('bankBranch', function($query){
 $query->whereIn('id',Auth::user()->bankBranch()->lists('id'));
})->get();