我正在尝试使用pivot访问多对多关系的中间表属性,但它返回空值。
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 :(得分: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 :(得分:1)
默认情况下,只有模型键才会出现在数据透视对象上。如果数据透视表包含额外属性,则必须在定义关系时指定它们:
public function packages()
{
return $this->belongsToMany('App\Package')->withPivot('created_at');
}
public function users()
{
return $this->belongsToMany('App\User')->withPivot('created_at');
}
答案 2 :(得分: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();
希望这有帮助。