SQL query problem in laravel

2

I'm not really understanding these queries in laravel php. I did a search of cities states where when searching the state lists the corresponding city, but it does not find the id of the table if the relationships were done correctly.

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

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

States Model:

<?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');
  }
}
    
asked by anonymous 04.10.2017 / 18:49

1 answer

3

RESOLVED:

I was able to resolve 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);
}
    
04.10.2017 / 18:54