【发布时间】:2016-09-20 21:48:51
【问题描述】:
我在 Laravel 4.2 中使用 Eloquent ORM 时遇到问题
我有 2 个表,银行和 bank_accounts
在银行中,我有银行的 ID,在 bank_accounts 表中,我有 bank_id,它是指向银行表的外键。
我已经为此苦苦挣扎了几个小时,并且在 Laravel 文档中没有任何运气。
我有两个模型:
银行账户模型:
<?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');
}
}
银行模型:
<?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');
}
}
我需要列出用户添加的帐户并显示其相关银行的名称,但不知道该怎么做。
到目前为止,我在控制器中:
public function showCuentas()
{
$results = Cuentas::all();
return View::make('content.bancos.list_bancos', array('bancos' => $results));
}
还有观点:
<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>
但它总是在表格中显示第一家银行的名称,而不是相关的。
感谢任何帮助
【问题讨论】:
-
$banco->banco->first()->banco?为什么会在这里? -
我使用 $banco 作为对象,然后 ->banco 作为模型内部遵循 ->first() 的方法来获取与 bank_id 和 -> 匹配的第一条记录(也是唯一的)末尾的 banco 是表中包含银行名称的字段
-
试试
{{ $banco->banco->banco }}:-)
标签: php mysql laravel laravel-4 eloquent