我有两个模型User
和Driver
user
可以注册任意数量的驱动程序drivers
在驱动程序表中我有agent_id
,我想列出所有users
及其注册的驱动程序数
在我的Usercontroller中我想获取代理商注册的驱动程序的数量
public function index(Request $request)
{
$users = User::all();
$registration_centers = RegistrationCenter::all();
$drivers_registered = Driver::where('agent_id' , $agent_id)->count(); //something like this but i don't have agent_id to query with
return view('agents', compact('users', 'registration_centers', drivers_registered));
}
Drver Model
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Driver extends Model
{
use SoftDeletes;
protected $fillable = ['agent_id','registration_center','event_name','registration_id','profile_photo','first_name','last_name',];
}
和用户模型
<?php
namespace App;
use App\Driver;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use SoftDeletes, HasApiTokens, Notifiable;
protected $fillable = ['name', 'email', 'phone_number','password','address_city_village','address_state','image','registration_center','status'];
protected $hidden = ['password', 'remember_token','created_at','updated_at','deleted_at'];
protected $dates = ['deleted_at'];
}
我想在列表视图中显示所有users
并显示每个用户的驱动程序数
<ul>
@foreach (users as user)
<li>User: {{user->name}}
Total Drivers: {{$user->drivers_count}}
</li>
@endforeach
</ul>
谢谢
答案 0 :(得分:1)
示例AgentController:
public function index(Request $request, $agenId){
$users = User::all();
$registration_centers = RegistrationCenter::all();
$drivers_registered = Driver::where('agent_id' , $agenId)->count();
return view('agents', compact('users', 'registration_centers',
'drivers_registered'));
}
this blade
<p> {{ $drivers_registered }} </p>
答案 1 :(得分:1)
假设agent_id
是将用户与驱动程序联系起来的关键...您非常接近我认为您要求的内容。
但是,在UserController的索引方法的第一行,我会更新
$users = User::all();
到
$users = User::withCount('drivers')->all();
并将驱动程序关系添加到User模型。
所以添加了关系的用户模型现在将是
class User extends Authenticatable
{
use SoftDeletes, HasApiTokens, Notifiable;
protected $fillable = ['name', 'email', 'phone_number','password','address_city_village','address_state','image','registration_center','status'];
protected $hidden = ['password', 'remember_token','created_at','updated_at','deleted_at'];
protected $dates = ['deleted_at'];
public function drivers(){
$this->hasMany('App\Driver', 'agent_id');
}
}
您可以从控制器中删除以下行,但这取决于您...
$drivers_registered = Driver::where('agent_id' , $agent_id)->count();