0

I have this Eloquent query:

$datos = Medidore::select([
    'medidores.*',
    'empresas.name as empresa',
    'tipo_medidor.descripcion as tipomedidor',
    'tipo1.descripcion as canal_1',
    'tipo2.descripcion as canal_2'])
    ->join('empresas', 'medidores.empresa_id', '=', 'empresas.id')
    ->join('tipo_medidor', 'medidores.cod_tipo_medidor', '=', 'tipo_medidor.id')
    ->join('tipo_canal_med as tipo1', 'medidores.canal1', '=', 'tipo1.id')
    ->join('tipo_canal_med as tipo2', 'medidores.canal2', '=', 'tipo2.id')
    ->whereNull('medidores.deleted_at')
    ->get();

It is not bringing any data, why? If I do this $datos = Medidore::all(); of course it works, with thrash data tho, because I need the joins.

How can I di that query with Eloquent, joins and SoftDeletes?

1 Answer 1

1

You need to set up your relationships: https://laravel.com/docs/5.6/eloquent-relationships

In your Medidore class, it would be

public function empresa(){
  return $this->belongsTo(Empresa::class);
}

Ultimately your query will look something like this, assuming I understand your relationships right:

Medidore::with('empresa', 'tipoMedidor', 'canal1', 'canal2')->get();

Eloquent will automatically factor in soft deletes. The returned collection of Medidore objects will already have loaded $medidore->empresa from the database

Sign up to request clarification or add additional context in comments.

4 Comments

Nice, I'm still learning. I got now the message Call to undefined relationship [empresa] on model [App\Models\Mantenedores\Medidores\Medidore
You will have to put that relationship function into the Medidore class, as well as the other relationship functions like tipo
Hmm, that means that I'll have to change a lot of things, code and database. Laravel is expecting the id calledmedidore_id, jesus... I'm back to query builder.
@pmirnd you can use the additional parameters to define the columns, if needed. Something like return $this->belongsTo(Empresa::class, "empresa_id"); or $this->belongsTo(TipoMedidor::class, "cod_tipo_medidor", "id");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.