2017-06-12 79 views
0

我有两张表 - 两者都是遗留的。Laravel 5.4雄辩关系不太对

一张桌子,国家,刚刚v领域:

entry (index field) 
Countryname 
Abbrev 

我的另一台是PCustomers它(其中包括)具有

Reference (index field) 
country (the foreign key) 

我有两个模型建立:

class Countries extends Model 
{ 
    protected $table="Countries"; 
    protected $primaryKey = 'entry'; 

    function pcustomer() 
     { 
      return $this->hasMany('App\PCustomer','country','entry'); 
     } 
} 

and

class PCustomer extends Model 
{ 
    protected $table = 'p_customers'; 
    protected $primaryKey = 'Reference'; 

    public function country() 
     { 
      return $this->hasOne('App\Countries','entry','country'); 
     } 

    public function addnew(Request $request) 
     { 

     } 
} 

要尝试了这一点,我放在一个控制器:

public function PCustomers() 
     { 
      $customer = PCustomer::find(5955)->country; 
      dd($customer); 
     } 

我知道5955存在,它的国家是74

的DD返回74,但没有别的。

如果我把国家,所以它成为

$customer = PCustomer::find(5955); 

我得到通常和正确的收集与全域。

我认为应该发生的是 - >国家,我会得到记录的细节加上3场来自全国各地,而不仅仅是74

帮助赞赏!

+0

我发现我可以用下面的行得到这样的: '$客户= PCustomer :: where('Reference',5955) - > with('country') - > get();' 但这似乎与文档不一致。 – Jim

+0

不,如果你做' - >国家',那么只有国家记录将被退回。这是预期的行为。你的解决方案是正确的,只不过你最好用'first()'替换'get()',因为你只需要一条记录。当然,你可以坚持你所做的,但它会返回一个[集合](https://laravel.com/docs/5.4/eloquent-collections)而不是记录。 – Fahmi

回答

0

我发现我可以用下面的行得到这样的:

$customer = PCustomer::where('Reference',5955)->with('country')->get(); 

但这似乎有差异的文档