【问题标题】:Laravel Access to several tablesLaravel 访问多个表
【发布时间】:2015-11-30 07:43:12
【问题描述】:

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

<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

&lt;td&gt;{{$exercise-&gt;activity_id}}&lt;/td&gt; 线上,这只是另一个名为activity_type 的表的外键,它有一个id 和一个名称,所以我想要显示的是带有这个id 的名称。

我该怎么做?

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.1


    【解决方案1】:

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

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

    那你就可以这样使用了

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

    【讨论】:

    • return $this->belongsTo('App\ActivityType', 'activity_id','id'); 'foreign_key' 是第二个参数。
    • 谢谢!这就是解决方案
    • 如果这个解决方案没问题,那么把它作为接受的答案,这将有助于其他已经面临这个问题的人
    【解决方案2】:

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

    在你的Exercise.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');
        }
    }
    

    之后,您可以通过这种方式访问​​ Activity 属性:

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

    【讨论】:

      猜你喜欢
      • 2017-04-17
      • 2012-08-14
      • 2018-11-21
      • 1970-01-01
      • 2021-01-26
      • 2021-04-10
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      相关资源
      最近更新 更多