Select columns in different tables

Asked

Viewed 105 times

2

I am using Laravel 5.3 and would like to use columns of 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 a consultation

  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('App\Endereco', 'end_cep','cep');
    }
}

My controller

$objeto = Cliente::with('endereco')
                    ->select('id','nome','end_cep', 'rua')
                    ->get();

But it’s giving as if the street column is unknown

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'street' in 'field list

I’m a beginner in Laravel

How could I fix this?

  • Would not be end_cep instead of cep after the WHERE in your consultation?

  • Yes. I gave a wrong

  • If I’m not mistaken you can’t put the column rua no select, because with will return you an address object that you can access with $objeto->endereco->rua.

  • 1

    That’s right. It worked. You can add as an answer, please

1 answer

1


Your select does not need to pass the names of the columns you have in the address table, in this case you are passing the column rua and there is no need.

Remove it from select and call the object as follows:

$objeto->endereco->rua

The address is returned as an object and thus ai should work.

Browser other questions tagged

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