雄辩关系不能从查找中获得列结果


Eloquent Relationships Can't get Column result from Lookup

我就是搞不懂《雄辩》里的人际关系。当我以为我已经得到它时,我绊倒了。

就像这里一样,我想列出每个Headquarters_Pay_Data项的country字段。

模型;

<?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 ?

由于您的雄辩关系方法,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模型的情况下,但这不是必需的。