雄辩的关系无法从查找中获得列结果

时间:2015-08-18 10:26:33

标签: php oop laravel laravel-5 eloquent

我无法理解Eloquent中的关系。就在我想我得到它的时候,我绊倒了。

就像这里一样,我想列出每个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 个答案:

答案 0 :(得分:1)

由于您的雄辩关系方法,postcode字段是Postcode_Quarter模型上另一个模型(Headquarters_Pay_Data)的实例。所以$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的情况下,但不需要这样做。< / p>

请阅读documentation以获取有关预先加载的更多信息。