如何从另一个 table 获取所有用户数据并将它们包含在 laravel 的用户列表中?

How to get all the user data from another table and include them on user list in laravel?

我在我的用户中显示我的用户时使用了 2 tables>index.blade

这2

用户table

和COLLECTOR_MEMBERStable

结果是这样

现在我的问题是我想连接到另一个叫 table 的

佣金table

达到这个结果

型号

佣金模型

用户

收款会员

USER控制器索引函数

public function index(Request $request)
{
    $users = User::all();           
    $admins = User::whereHas('roles', function ($q) {
      $q->where('roles.name', '=', 'admin');
    })->get();

    $collectorList = User::whereHas('roles', function ($q) {
      $q->where('roles.name', '=', 'collector');
    })->with('collectorList')->get();

    $borrowers = User::whereHas('roles', function ($q) {
      $q->where('roles.name', '=', 'borrower');
    })->get();

    $userProfile = Auth::user()->id;

    if (Auth::User()->hasRole(['borrower','collector'])){
        return redirect('dashboard/profile/'.$userProfile);
    }

    return view('dashboard.users.index', compact('users','profile'))
            ->with('admins',$admins)
            ->with('borrowers',$borrowers)
            ->with('collectorList',$collectorList);
            // ->with('collectorBorrowers',$collectorBorrowers);
}

如何显示佣金 table 中的 commission_amount 列?像这样制作我的列表

您可以使用 sum 聚合函数,您的代码应如下所示。

$collectorList = User::whereHas('roles', function ($q) {
      $q->where('roles.name', '=', 'collector');
    })->with(['collectorCommission' => function($query) {
          $query->sum('commission_amount');
}])->get();

假设您的用户模型中存在这种关系

public function collectorCommission() [
   return $this->hasMany('App\Commissions', 'user_id');
}

You cant use belongsToMany relationship since this relationship requires you an intermediary table in your second argument.

考虑到一个用户有很多佣金,你应该使用 hasMany 关系。