【发布时间】:2017-02-24 08:13:11
【问题描述】:
好的,我有一个问题。我正在编写一个非常复杂的报告,界面使用 Laravel 5.2。现在的问题是,根据某些条件,用户并不总是需要填写所有参数。但是,为了简单起见,我这样做是为了让报告始终接收完整的参数集。所以我有三张桌子:
tblReportParam
ID
ParamName
DefaultValue
tblReportParamValue
ParamID
ReportID
Value
tblReport
ID
UserName
现在,我有一个可行的解决方案,但出于某种原因,我感觉我应该能够更好地利用模型和关系。我基本上只有我的模型和控制器,并使用 SQL 解决了整个问题。
感觉有点接近this,但不完全一样。所以基本上,您需要始终加载/保存所有参数。如果参数 x 实际上是由用户定义的,那么您使用他的定义,否则您将使用 tblReportParam 中定义的默认值。任何人都知道如何做到这一点?
编辑:
好的,所以我检查了 Eddy 的答案并尝试在我们的系统中使用它,但我的另一位同事开始在 tblReport 和 tblReportParam 表之间实现多对多关系,其中 tblReportParamValue 作为枢轴所以我'我在为我们的系统调整这个解决方案时遇到了一些困难。这是两个模型:
class ReportParam extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'tblReportParam';
protected $primaryKey = 'ID';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['ID', 'NomParam', 'DefaultValue'];
public function renourapports()
{
return $this->belongsToMany('App\Report');
}
}
class Report extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'tblReport';
protected $primaryKey = 'ID';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['ID', 'NoEmploye', 'NoClient', 'NoPolice', 'DateCreation', 'DateModification', 'runable', 'DernierEditeur'];
public $timestamps = false;
public function params()
{
return $this->belongsToMany('App\ReportParam ', 'tblReportParamValue', 'ReportID', 'ParamID')->withPivot('Valeur');
}
}
现在这实际上是一个非常简洁的解决方案,但它仅在参数实际位于数据透视表中时才有效(即关系实际存在)。我们想要的是对于不在数据透视表中的参数,我们只需要它们的默认值。在这种情况下,Eddy 的解决方案可以工作吗?
【问题讨论】:
标签: php laravel relationships