简体   繁体   中英

How call result Database Query from Model to API Controller Laravel

I have this query in API Controller (FormController.php) that call 2 Model which they are related One to many.

public function getFormD($electionId, $model, $wilayahId)
    {
      $result = FormDImageDetail::with('formd_image')
      ->where('jenis_pemilihan', $electionId)
      ->where('jenis_form', $model)
      ->where('id_wilayah', $wilayahId)
      ->where('versi', function($query) use($electionId) {
        $query->select(DB::raw('max(versi)'))
        ->from('formd_image')
        ->whereColumn('id_wilayah', 'formd_image_detail.id_wilayah')
        ->where('flag_aktif', true)
        ->where('jenis_pemilihan', $electionId);
      })
      ->orderBy('no_lembar')
      ->paginate(100);
      return $result;
    }

First Model (FormDImage.php)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FormDImage extends Model
{
    protected $table = 'formd_image';

}

My second Model (FormDImageDetail.php)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FormDImageDetail extends Model
{
    protected $table = 'formd_image_detail';

    public function formd_image(){
      return $this->belongsTo('App\Models\FormDImage', 'id_wilayah', 'id_wilayah');
    }
}

For now i wanna move query SQL from API Controller to Model and using DB::Raw SQL then call it in this API Controller.

How should i do?

The correct method is put your business logic and other functions in your controller as you have done. Why do you need to move SQL into model. Model is the relation to DB and your app. If you want encapsulate the query, please try to do it using repository pattern. This link will be helpful for you.

https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/#Criteria_Queries

https://medium.com/employbl/use-the-repository-design-pattern-in-a-laravel-application-13f0b46a3dce

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM