【问题标题】:Issue with Eloquent Relationships in Laravel 4.2Laravel 4.2 中 Eloquent 关系的问题
【发布时间】: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-&gt;banco-&gt;first()-&gt;banco ?为什么会在这里?
  • 我使用 $banco 作为对象,然后 ->banco 作为模型内部遵循 ->first() 的方法来获取与 bank_id 和 -> 匹配的第一条记录(也是唯一的)末尾的 banco 是表中包含银行名称的字段
  • 试试{{ $banco-&gt;banco-&gt;banco }} :-)

标签: php mysql laravel laravel-4 eloquent


【解决方案1】:

您不应该使用延迟加载,因为对于每个Cuenta,您的数据库中都会有另一个查询。改用急切加载:

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

然后你去:

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
    ....
}

【讨论】:

  • 非常感谢,虽然我可以简化查询(这就是为什么使用 Eloquent 而不是 Query Builder 的原因)但没有设法做到这一点。它现在正在工作,我已经接受了您的回答并给了您反馈。再次感谢!
  • 不知何故我没有看到你的答案。可以节省我写几乎相同的时间(急切加载除外)。
【解决方案2】:

好吧,文档说 Model::belongsTo (laravel 4.2) 方法

belongsTo( string $related, string $foreignKey = null, string $otherKey = null, string $relation = null)

我看到你传递给你的函数 Cuentas::belongsTo() 的第二个参数是 'id_cuentos' 但是在 Bancos 类中,主键属性说主键的名称是 'id'。

protected $primaryKey = 'id';

是不是有什么问题?

【讨论】:

  • 感谢您的提示,但没有奏效。仍然显示表的第一条记录而不是相关的记录
  • belongsTo() 的第二个参数是外键列的名称 - 而不是目标表主键列的名称。
【解决方案3】:

public function Banco() 是一个belongsTo 关系,将返回一个Bancos 对象——而不是它们的集合。因此,当您在该对象上调用 -&gt;fist() 时,它不是 Collection::fist() 函数 - 它是 Bancos::first()。这就是为什么你总是从 Bancos 模型中获得第一个条目的原因。

在您的 foreach 循环中,$banco 是一个 Cuentas 对象。而$banco-&gt;banco 是您需要的相关 Bancos 对象。因此,如果您的 Bancos 对象中有属性 $banco - 您只需在模板中调用

{{ $banco->banco->banco }}

正如其他人在回答中提到的那样,您应该将Banco() 重命名为banco() 或致电{{ $banco-&gt;Banco-&gt;banco }}

附带说明:您的命名风格非常混乱。为什么将Cuentas 集合称为$bancos

我会重命名一些东西:

  • function Banco() => function banco()
  • array('bancos' =&gt; $results) => array('cuentas' =&gt; $results)
  • @foreach($bancos as $banco) => @foreach($cuentas as $cuenta)
  • {{ $banco-&gt;banco-&gt;banco }} => {{ $cuenta-&gt;banco-&gt;banco }}

另外(如果可能的话)我会将属性Bancos::banco 重命名为Bancos::name,这样您就可以调用{{ $cuenta-&gt;banco-&gt;name }} 而不会混淆审阅者。

【讨论】:

    【解决方案4】:

    我很确定事情是区分大小写的,您在模型中使用 Banco,在视图中使用 Banco。

    【讨论】:

    • 不是这样,如果你看到我通过执行 Bancos::all() 调用模型的代码,那么在我看来,我会得到对象 $banco 并从模型中调用 ->banco 方法
    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 2015-06-18
    • 2017-04-28
    • 1970-01-01
    • 2015-01-27
    • 2015-07-05
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多