Laravel访问多个表


Laravel Access to several tables

我在访问多个表中相关的数据时遇到问题,这里是我的代码:

<table class="table table-striped">
    <thead>
        <th>Ejercicio</th>
        <th>Unidad</th>
        <th>Descripcion</th>
        <th>Tipo actividad</th>
        <th>Operaciones</th>
    </thead>
    @foreach($exercises as $exercise)
    <tbody>
        <td>{{$exercise->name}}</td>
        <td>{{$exercise->unit}}</td>
        <td>{{$exercise->description}}</td>
        <td>{{$exercise->activity_id}}</td>
        <td>
            <?php echo link_to('exercise/edit/'.$exercise->id, $title = 'Editar', $attributes = array('class' => 'btn btn-primary'), $secure = null); ?>                
        </td>
    </tbody>
    @endforeach
</table

<td>{{$exercise->activity_id}}</td>行,这只是另一个名为activity_type的表的外键,它有一个id和一个名称,所以我想显示的是带有这个id的名称。

我该怎么做?

首先在基础模型上编写一个关系。这里我给你举一个属于关系的例子

public function ActivityRelation()
{
    return $this->belongsTo('App'ActivityType', 'id', 'activity_id');
}

然后你可以像一样使用

{{$exercise->ActivityRelation->name}}

您需要在模型中建立关系。

在您的练习中.php

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Exercise extends Model
{
    public function activity_type()
    {
      return $this->belongsTo('App'ActivityType','activity_type');
    }
}

在ActivityType.php中,这在您的情况下并不是真正需要的,但如果您想获得相反的关系。

<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class ActivityType extends Model
{
    public function exercises()
    {
      return $this->hasMany('App'Exercise');
    }
}

之后,您可以通过以下方式访问"活动"属性:

<td>{{$exercise->activity_type->name}}</td>