sql - 在 Eloquent 数据库 Laravel 中按最大值搜索
问题描述
如何在我的 API 控制器中将此原始 SQL 转换为 Eloquent 数据库?
我尝试的是我想从我的 API 控制器的两个表中获取数据。
第一个:formc_image 表,它是关于数据的一般信息
第二:formc_image_detail 是数据的细节和路径
它们通过 ID 关联。
这是我的 API 控制器 FormCController.php
SELECT *
FROM formc_image_detail
WHERE id_tps=$id_tps AND jenis_pemilihan=$election_id
AND versi = (SELECT MAX(versi) FROM formc_image WHERE id_tps=id_tps AND jenis_pemilihan=$election_id)
ORDER BY no_lembar ASC
这是我的模型 FormCImageDetail
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImageDetail extends Model
{
protected $table = 'formc_image_detail';
public function formc_image(){
return $this->belongsTo('App\Models\FormCImage');
}
}
这是我的 FormCImage 模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImage extends Model
{
protected $table = 'formc_image';
}
我在我的 API 控制器中编写了这段代码:
return response(FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->orderBy('no_lembar', 'ASC')->paginate(100)->jsonSerialize(), Response::HTTP_OK);
但它仍然错误。
这是我的迁移:
Schema::create('formc_image', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->string('jenis_pemilihan');
$table->timestamps();
}
Schema::create('formc_image_detail', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->integer('no_lembar');
$table->string('jenis_pemilihan');
$table->char('url_image', 100);
$table->timestamps();
}
解决方案
用这个:
return FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->where('versi', function($query) use($election_id) {
$query->select(DB::raw('max(versi)'))
->from('formc_image')
->whereColumn('id_tps', 'formc_image_detail.id_tps')
->where('jenis_pemilihan', $election_id);
})
->orderBy('no_lembar')
->paginate(100);