Question :
I’m using Laravel 5.3 and would like to use columns from two different tables related to foreign key:
For example:
Client table
id | nome | end_cep
1 | carlos | 69084555
2 | Maria | 69088555
Address table
cep | rua
69084555 | Rua grande vitória
69088555 | Rua Programacao
I would like to make an inquiry
SELECT id, nome, end_cep, e.rua FROM cliente, endereco e WHERE end_cep = e.cep
My Model
class Cliente extends Model
{
public function cliente(){
return $this->belongsTo('AppEndereco', 'end_cep','cep');
}
}
My controller
$objeto = Cliente::with('endereco')
->select('id','nome','end_cep', 'rua')
->get();
But it’s getting as if the street column was unknown
SQLSTATE [42S22]: Column not found: 1054 Unknown column ‘street’ in ‘field
list
I’m new to Laravel
How could I solve this?
Answer :
Your select does not need to pass the names of the columns it has in the address table, in this case you are passing the rua
column and it is not necessary.
Unselect the select and call the object as follows:
$objeto->endereco->rua
The address is returned as an object and so it should work there.