在雄辩的数据库Laravel中按价值最大值进行搜索

时间:2018-12-07 02:47:08

标签: sql database laravel eloquent

如何在我的API控制器中将原始SQL转换为雄辩的数据库?

我尝试过的是我想从我的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();
}

1 个答案:

答案 0 :(得分:1)

使用此:

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);