PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 20, 2022

[FIXED] How to map exting table to a model in laravel

 February 20, 2022     eloquent, laravel, mysql, php     No comments   

Issue

I have mysql table named casa that have a primary key named casa_id. I setted up a model:

 class Casa extends Model
{
 protected $table = 'casa';
public $casa_id;
public $anuncio_id;
public $banheiros;
public $capacidade_garagem;
public $dormitorios;
public $piscina;
public $preco;
public $dir_id;
public $cep;
public $numero_fotos;
public $visualizacoes;
public $ativo;
public $descricao;

public $timestamps = false;

protected $connection = 'eloquent_db';


}

Executing this code

$casa = \App\Casa::find($id);

I get his error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'casa.id' in 'where clause' (SQL: select * from casa where casa.id = 238 limit 1)

I don't know Eloquent but I assume that some conventioin is missing. Can you give the directives to map my existing table to a model so that I can use Eloquent. I am more of database first guy but I'm learning web api and don't want to deviate from my path and start writing SQL commands. My table columns have the exact names of my model.

code for the operation I want to perform:

$casa = \App\Casa::find($id);
$casa->dormitorios = 5;
$casa->save();

Solution

Change it to:

class Casa extends Model{
  protected $table = 'casa';
  protected $primaryKey = 'casa_id';
  protected $connection = 'eloquent_db';
  public    $timestamps = false;
} 

$casa = \App\Casa::find($id);


Answered By - voodoo417
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing