我只是無法讓我的頭在關係中的雄辯。就在我認爲我已經掌握了它的時候,我就絆倒了。雄辯的關係不能從查找中得到列結果
像這裏,我想列出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
?
其實..我發現我的問題是因爲我的付款表中沒有對應的查找值的郵編。我剛剛發現它。我應該也許開始使用TDD!不過,這也是一個很好的建議。 – mikelovelyuk
@alexrussell謝謝 – Sanoob
@Shanoop沒有問題 - 答案很有道理,只是需要一些解釋,說明究竟發生了什麼。看起來愚蠢的增加一個單獨的答案與相同的實際答案,但只是更多的描述。 – alexrussell