好的,所以我有一个问题。我正在编写一份非常复杂的报告,并且界面使用Laravel 5.2。现在的事情是,根据某些条件,用户并不总是需要填写所有参数。但是,为了简单起见,我做了这样的报告,无论发生什么情况,报告都会收到一整套参数。所以,我有三个表:使用Laravel 5.2中的关系填充默认值的参数
tblReportParam
ID
ParamName
DefaultValue
tblReportParamValue
ParamID
ReportID
Value
tblReport
ID
UserName
现在,我有一个可行的解决方案,但由于某些原因,它只是感觉我应该能够更好地利用模型和关系。我基本上只有我的模型和控制器,并使用SQL解决了整个问题。
这感觉有点接近this,但不完全。所以基本上,您需要始终加载/保存所有参数。如果参数x实际上是由用户定义的,那么您使用他的定义,否则您将使用tblReportParam中定义的默认值。任何人有任何想法如何做到这一点?
编辑:
好了,所以我检查艾迪的答案,并试图在我们的系统的工作,但我的另一个同事开始实施与tblReportParamValue的tblReport和tblReportParam表之间的许多一对多的关系作为支点,所以我在适应我们系统的这个解决方案时遇到了一些困难。以下是两种模式:
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的解决方案能在这种情况下工作吗?
您的解决方案是否可以用于多对多的关系? – Osuwariboy
当然,但你将不得不改变第二个功能来检查你的收藏。 – EddyTheDove
我在查看你的意思时遇到了一些问题。你可以发布一些代码吗?提前致谢 :)。 – Osuwariboy