最后一个post查询左连接



我有三个表

用户
  1. <
  2. 护照/gh><
  3. 部分/gh>

我想获得用户和他最近的护照。用户在一个部分中,可以有多个(历史)护照。有效护照,最长护照日期

用户
Table 
...
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->foreignId('section_id')->nullable()->constrained();
...

Table
...
$table->string('title');
$table->string('description');
...

护照
...
$table->date('passportDate')->nullable();
$table->string('firstName')->nullable();
$table->string('middleName')->nullable();
$table->string('lastName')->nullable();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
...

我想为每个用户获取一组字段:

"email" "section_title"  "firstName"  "middleName" "lastName"

我的请求:

$users = User::select('users.*', 'sections.title', 'passports.firstName', 'passports.middleName', 'passports.lastName')
->leftJoin('sections', 'sections.id', 'users.section_id')
->leftJoin('passports', 'user_id', 'users.id')
->orderBy('firstName')
->get();

问题是,如果用户有多个护照,则用户的条目是重复的。我需要获取每个用户的最新(max passportDate)护照数据

可以试试这个:

$users = User::select('users.*', 'sections.title')
->leftJoin('sections', 'sections.id', 'users.section_id')
->orderBy('firstName')
->get();
$users->each(function ($item, $key){
$item->passports = Passport::select('firstName', 'middleName', 'lastName')
->where('user_id', $item->id)
->get();
}

护照数据将是一个单独的数组你可以为它添加任何条件

您可以使用关系来获取最新的护照(或获取您的部分或所有护照)

在你的用户模型上定义关系:

public function latestPassport() {
return $this->hasOne(Passport::class)->latest('passportDate');
}

然后将关系添加到查询中:

$users = User::select()
->with(['sections', 'latestPassport'])
->orderBy('firstName')
->get();

最新更新