2015-11-30 25 views
0

我有在訪問到在多個表中相關數據,在這裏我的代碼的問題:行<td>{{$exercise->activity_id}}</td>Laravel訪問幾個表

<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 

這只是另一個表的外鍵名爲activity_type有一個ID和一個名稱,所以我想要顯示的是這個ID的名稱。

我該怎麼做?

回答

1

先寫你的基地model.Here上的關係我給你舉個例子屬於關係

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

然後你可以使用這樣的

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

回報$這個 - >屬於關聯( '應用程序\ ActivityType', 'ACTIVITY_ID', 'ID'); 'foreign_key'是第二個參數。 –

+0

謝謝!這使得解決方案 – user3557451

+0

如果這個解決方案是好的,那麼將其作爲可接受的答案,這將有助於已經面對這個問題的其他人 –

0

你需要建立在你的模型關係。

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

在此之後,你可以訪問活動屬性是這樣的:

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