Problem in SQL query in the Laravel

Asked

Viewed 75 times

2

I’m not really understanding these queries in php Standard. I searched cities states where when searching the state lists the corresponding city, but it does not find the table id if the relationships were done correctly.

Municipios Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Municipios;
use App\Estados;

class MunicipiosController extends Controller
{
  private $estadoModel;

  public function __construct(Estados $estado)
  {
    $this->estadoModel = $estado;
  }

  public function index()
  {
    $municipios = Municipios::with('estados')->get();
    return response()->json($municipios);
  }
  // retorna todos os municípios cadastrados
  public function show($id)
  {
    $municipios = Municipios::with('estados')->find($id);

    if(!$municipios) {
      return response()->json([
        'message'   => 'Não há resultados',
      ], 404);
    }

    return response()->json($municipios);
  }
  // retorna os municípios por estado
  public function getMunicipios($estados_id)
  {
    $estado = $this->estadoModel->find($estados_id);
    $municipios = $estado->municipios()->getQuery()->get(['municipios_id','nome']);
    return Response::json($municipios);
  }
}

Municipios Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Municipios extends Model
{
  protected $fillable = ['nome','cep','estados_id'];
  protected $primaryKey = 'municipios_id';
  public $timestamps = false;

  public function estados()
  {
    return $this->belongsTo('App\Estados');
  }
}

Controller States:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Estados;

class EstadosController extends Controller
{
    //
    public function index ()
    {
      $estados = Estados::all();
      return response()->json($estados);
    }
}

Model States:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Estados extends Model
{
  protected $fillable = ['nome','sigla'];
  protected $primaryKey = 'estados_id';
  public $timestamps = false;

  public function municipios()
  {
    return $this->hasMany('App\Municipios');
  }
}

1 answer

3

RESOLVED:

I managed to solve with the following function:

public function getMunicipios($estados_id)
{
    $municipios = DB::table('municipios')
        ->where('estados_id','=', $estados_id)
        ->orderBy('nome','asc')
        ->get();
    return Response::json($municipios);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.