2013-05-09 58 views
1

晚上好,我和Laravel玩了一下,我有這種情況。我有2個模型和3個表格來顯示來自pacient的生命體徵。獲取關鍵點和重新分配表的列值Laravel 3

Table pacient: 
id 
names 
birthdate 

Table vital_sign: 
id 
description 
unit 

table pacient_vital_sign 
id 
pacient_id 
vital_sign_id 
first_value 
second_value 
date_time_taken 

而且2種型號:

class Pacient extends Eloquent{ 
     public static $timestamps = false; 

     public function vital_signs(){ 
      return $this->has_many_and_belongs_to('VitalSign', 'pacient_vital_sign', 'pacient_id', 'vital_sign_id'); 
     } 
    } 

class VitalSign extends Eloquent{ 
     public static $timestamps = false; 
     public static $table = 'vital_signs'; 
     public function pacients(){ 
      return $this->has_many_and_belongs_to('Pacient', 'pacient_vital_sign', 'vital_sign_id', 'pacient_id'); 
     } 
    } 

而對於我的看法我要送我要顯示其生命體徵pacient:

$pacient = Pacient::where('active', '=', 1)->first(); 

因此,基於該documentation我可以這樣做來顯示關鍵表格數據:

@foreach($pacient->vital_signs as $sv) 
    <tr> 
     <td>{{ $sv->pivot->date_time_taken }}</td> 
     <td>{{ $sv->description }}</td> 
     <td>{{ $sv->pivot->first_value }} &nbsp; {{ $sv->pivot->second_value }}</td> 
    </tr> 
    @endforeach 

但是這樣,date_time_taken值,first_value或second_value都不顯示。顯示說明。現在

,如果我做這樣的事情

@foreach($pacient->vital_signs()->pivot()->get() as $sv) 
    <tr> 
     <td>{{ $sv->date_time_taken }}</td> 
     <td>{{ $sv->description }}</td> 
     <td>{{ $sv->first_value }} &nbsp; {{ $sv->second_value }}</td> 
    </tr> 
    @endforeach 

date_time_taken,FIRST_VALUE和secon_value顯示,但我不知道如何扭轉的關係,以顯示相關的表列中的值,在這種情況下, ,來自vital_sign表的描述

所以我這兩種情況下,我失去了一些東西。有任何想法嗎?我很想念什麼?

感謝

+0

在你的第一個'@ foreach'中,如何使用'$ sv-> pivot() - > first_value'? – 2013-05-09 08:21:29

+0

嘗試並引發此錯誤:方法[數據透視表]沒有在Query類上定義 – Cheluis 2013-05-09 14:26:28

+0

啊,是的,我想這是有道理的。我可以肯定地告訴你,第二個例子不會包含'description',因爲它不在數據透視表中。爲什麼你的第一個例子不起作用,我很難確定。 – 2013-05-09 15:01:25

回答

2

上Docs:

By default only certain fields from the pivot table will be returned (the two id fields, and the timestamps). If your pivot table contains additional columns, you can fetch them too by using the with() method

所以在我的情況下,這兩種模式:

return $this->has_many_and_belongs_to('VitalSign', 'pacient_vital_sign', 'pacient_id', 'vital_sign_id')->with('col1', 'col2', 'coln'); 

,這將工作:

@foreach($pacient->vital_signs as $sv) 
    <tr> 
     <td>{{ $sv->pivot->date_time_taken }}</td> 
     <td>{{ $sv->description }}</td> 
     <td>{{ $sv->pivot->first_value }} &nbsp; {{ $sv->pivot->second_value }}</td> 
    </tr> 
@endforeach 
2

我發現這是有用的,但一個快速的附錄對於Laravel 4:

return $this->belongsToMany('Model','pivot_table','this_id','foreign_id')->withPivot('col1','col2'); 
return $this->belongsToMany('Model','pivot_table','this_id','foreign_id')->withPivot('col1','col2'); 
+0

Laravel API已經改變了,現在這是正確的答案。 – 2014-06-22 00:04:34