2016-11-14 59 views
0

嗨,我想訪問使用樞軸許多到很多關係的中間表屬性,但它返回空值。訪問laraval 5.2多對多樞軸。但它返回空

class User extends Modal 
{ 


    public function packages() 
    { 
     return $this->belongsToMany('App\Package'); 
    } 
} 


Class Package extend Model 

    { 

     public function users() 
     { 
     return $this->belongsToMany('App\User'); 
     } 


    } 

$package->pivot->created_at

但它返回null。

雖然我有一個與用戶相關的包。

+0

沒有足夠的信息有意義的答案 – Andrew

回答

1

試試這個:

class User extends Modal 
{ 


    public function packages() 
    { 
     return $this->belongsToMany('App\Package')->withTimestamps(); 
    } 
} 


Class Package extend Model 

    { 

     public function users() 
     { 
     return $this->belongsToMany('App\User')->withTimestamps(); 
     } 


    } 
1

默認情況下,只有模型密鑰將存在樞軸對象。如果您的數據透視表中包含額外的屬性,你必須定義的關係時指定它們:

public function packages() 
{ 
    return $this->belongsToMany('App\Package')->withPivot('created_at'); 
} 

public function users() 
{ 
    return $this->belongsToMany('App\User')->withPivot('created_at'); 
} 

Docs

1

請確保您有時間戳在表格中。

Schema::table('user_package', function (Blueprint $table) { 
     $table->timestamps(); 
    }); 

您可以通過在遷移

class User extends Modal 
{ 


    public function packages() 
    { 
    return $this->belongsToMany('App\Package')->withTimestamps(); 
    } 
} 


Class Package extend Model 
    { 

    public function users() 
    { 
    return $this->belongsToMany('App\User')->withTimestamps(); 
    } 


} 

加入,如果你不加入這一行的時間戳將不會被保存在數據庫中執行此操作。

return $this->belongsToMany('App\User')->withTimestamps(); 

希望這會有所幫助。

+0

我的表沒有時間戳。 –