2015-08-18 73 views
1

我只是無法讓我的頭在關係中的雄辯。就在我認爲我已經掌握了它的時候,我就絆倒了。雄辯的關係不能從查找中得到列結果

像這裏,我想列出country字段爲每個Headquarters_Pay_Data項目。

模型;

<?php 

namespace Datamate; 

use Illuminate\Database\Eloquent\Model; 

    class Headquarters_Pay_Data extends Model 
    { 
     // 
     protected $table = 'headquarters_pay_data'; 


     public function postcode() 
     { 
      return $this->hasOne('Datamate\Postcode_Quarter', 'postcode', 'Vendor ZIP'); 
     } 

    } 

而這一個;

<?php 

namespace Datamate; 

use Illuminate\Database\Eloquent\Model; 

use Datamate\Country; 

    class Postcode_Quarter extends Model 
    { 

     public $table = '201502_postcode'; 

     protected $fillable = ['country']; 

} 

我的控制器;

public function index() 
{ 
    // 
    $headquarters_pay_data = Headquarters_Pay_Data::limit(12)->get(); 

    foreach ($headquarters_pay_data as $key => $value) {  

     //print $value->postcode->country; //this returns an error. Trying to get property of non-object 
     print "<br><br>"; 
     print $value->getAttribute('Vendor ZIP'); 
     print "<br><br>"; 
     print $value->postcode; //this is JSON?! Why? 
     print "<br><br>"; 

    } 

示例打印出看起來像JSON的東西,即使我沒有要求使用JSON;

RH108PJ 

{"postcode":"RH108PJ","county":"E10000032","district":"","ward":"","health":"E18000008","gor":"J","parlc":"E14000652","locauth":"E07000226","wardcode":"E05007639","country":"E92000001","gor_new":"E12000008","pct":"E16000108"} 

澄清...如何爲每筆付款打印country

回答

1

由於您的雄辯關係方法,postcode字段是Headquarters_Pay_Data模型上的另一個模型(Postcode_Quarter)的實例。所以$value->postcode返回該模型(作爲PHP對象)。將模型轉換爲字符串(通過print)將使其嘗試將自身轉換爲用作字符串的最佳可能格式,該字符串是JSON字符串。

但是,您可以訪問該模型的屬性,因爲你希望國家可以做到以下幾點:

public function index() 
{ 
    $headquarters_pay_data = Headquarters_Pay_Data::with('postcode')->limit(12)->get(); 

    foreach ($headquarters_pay_data as $key => $value) {  
     print $value->postcode->country; 

    } 
} 

你會注意到,在這個例子中,我們爲了還使用with()以「急切加載」postcode關係。這通常會提高您的查詢效率,尤其是在您有很多Headquarters_Pay_Data型號以及不是很多Postcode_Quarter型號的情況下,但無需進行此項工作。

有關急切加載的更多信息,請閱讀documentation

+0

其實..我發現我的問題是因爲我的付款表中沒有對應的查找值的郵編。我剛剛發現它。我應該也許開始使用TDD!不過,這也是一個很好的建議。 – mikelovelyuk

+0

@alexrussell謝謝 – Sanoob

+0

@Shanoop沒有問題 - 答案很有道理,只是需要一些解釋,說明究竟發生了什麼。看起來愚蠢的增加一個單獨的答案與相同的實際答案,但只是更多的描述。 – alexrussell