Douglas Roos Douglas Roos - 6 months ago 20
MySQL Question

Issue with Eloquent Relationships in Laravel 4.2

I have an issue using Eloquent ORM in Laravel 4.2

I have 2 tables, banks and bank_accounts

In banks i have the ID of the bank and in the bank_accounts table i have bank_id and it's foreign key pointing to banks table.

I have been struggling with this for hours and looking in the Laravel Documentation without any luck.

I have two models:

BankAccounts Model:

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Cuentas extends Eloquent
{
protected $table = 'icar_cuentas';
protected $primaryKey = 'id';
public $timestamps = FALSE;

public function Banco()
{
return $this->belongsTo('Bancos','id_banco');
}
}


Banks Model:

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Bancos extends Eloquent
{
protected $table = 'icar_bancos';
protected $primaryKey = 'id';
public $timestamps = FALSE;

public function cuentasRelacionadas()
{
return $this->hasMany('Cuentas');
}
}


What i need is to list the accounts added by the user and show the name of its related bank but didn't figured out how to do it.

So far i have in the Controller:

public function showCuentas()
{
$results = Cuentas::all();

return View::make('content.bancos.list_bancos', array('bancos' => $results));
}


And the View:

<tbody>
@foreach($bancos as $banco)
@if($banco->activo == 'si')
{{-- */$estado = '<span class="label label-success">Activo</span>';/* --}}
@endif
@if($banco->activo == 'no')
{{-- */$estado = '<span class="label label-danger">Inactivo</span>';/* --}}
@endif
<tr>
<td><a href="{{ URL::to('cuentas/editar/'.Encryption::encode($banco->id)) }}"><i class="fa fa-edit"></i></a> | <a href="{{ URL::to('cuentas/eliminar'.Encryption::encode($banco->id)) }}" onclick="return confirma('Realmente deseas eliminar la cuenta {{ $banco->cuenta }}');"><i class="fa fa-trash-o"></i></a></td>
<td>{{ $banco->banco->first()->banco }}</td>
<td>{{ $banco->cuenta }}</td>
<td>{{ $banco->tipo }}</td>
<td>{{ $estado }}</td>
</tr>
@endforeach
</tbody>


But it always shows the name of the First Bank in the table instead of the related one.

Appreciate any help

Answer

You shouldn't use lazy loading, because, for each Cuenta you will have another query in your database. Use eager loading instead:

$results = Cuentas::with('banco')->get();

Then you go:

foreach($bancos as $banco) { //--> I think you should replace with cuentas, but it's up to you
    ....
    {{ $banco->banco->banco }} // also, terrible. Use banco.name instead. Give proper name to easily understand your code
    ....
}