2015-06-07 60 views
0

我有一個名爲Customer第二個兩分型一個是Website屬於關聯方法返回null

它們之間的關係是,Customer的hasMany WebsiteWebsite屬於關聯Customer

這就是我正在做的這個

class Website extends \Eloquent { 
    use SubscriptionBillableTrait; 

    protected $fillable = []; 

    protected $guarded = ['id']; 

    public function customermodel() 
    { 
     // Return an Eloquent relationship. 
     return $this->belongsTo('Customer') 
    } 

} 

Customer model

use Mmanos\Billing\CustomerBillableTrait; 
class Customer extends \Eloquent { 
    use CustomerBillableTrait; 
    protected $fillable = []; 

    protected $guarded = ['id']; 

    public function websites() { 
     return $this->hasMany('Website'); 
    } 

} 

當我試圖通過關係來訪問Customer這樣

$website = Website::find(1); 
return dd($website->customermodel); 

,則返回null

注:我使用Laravel 4

+0

不該」 t來自Eloquent關係的這些類名包含完全限定的名稱空間'$ this-> belongsTo ('App \ Customer');'(這很可能只適用於你使用Laravel 5,但你沒有指定)。 – Bogdan

+0

聲明關係時使用全名空間,例如'$ this-> hasMany('App \ Models \ Website');'和'$ this-> belongsTo('App \ Models \ Customer');'。那樣有用嗎? – Ohgodwhy

+0

@Bogdan我正在使用Laravel 4,所以我不認爲這會成爲觸發器 – Muhammad

回答

0

使用此

$website = Website::find(1)->with('customermodel'); 
return dd($website->customermodel); 
+0

兩個問題:首先,急切的加載不會有幫助。訪問'$ website-> customermodel'屬性將延遲加載數據,然後將其發送到'dd()'方法。其次,find()會返回模型。然後在模型上調用'()',這將返回一個新的查詢生成器,因此下一行將嘗試訪問查詢生成器上的'customermodel'屬性,這將引發異常。您需要在實際檢索數據的方法之前使用'with()'方法:'Website :: with('customermodel') - > find(1)'。 – patricus