我有这个会计项目,我需要在保存到数据库之前验证借方和贷方是否相等。
例如
accounts: [
{
id: 1,
account_id: 1,
debit: 1000
},
{
id: 2,
account_id: 5,
credit: 1500
},
{
id: 3,
account_id: 8,
debit: 500
}
]
顺便说一下,我正在使用axios和lodash。
axios.post('/api/journals', {
accounts : map(this.accounts, function(account) {
account_id: account.account_id,
debit: account.debit,
credit: account.credit
})
}
任何人都可以建议如何实施此验证规则。
答案 0 :(得分:0)
验证规则与Laravel或VueJS无关。您只需要使用lodash迭代accounts
数组,分别对借方和贷方编号求和,然后比较它们:
var debitSum = _.reduce(data.accounts, function(sum, account) {
return (account.debit || 0) + sum;
}, 0);
var creditSum = _.reduce(data.accounts, function(sum, account) {
return (account.credit || 0) + sum;
}, 0);
console.log('Debit: ' + debitSum + '; Credit: ' + creditSum);
if (debitSum !== creditSum) {
// Debit and credit sums do not match
} else {
// Debit and credit sums match
}
上面的代码使用_.reduce()
方法计算借方/贷方金额的总和。由于debit
和credit
密钥无法保证始终存在,因此我们使用||
运算符在其为假时指定值0(例如undefined
, null
,0
,空字符串等。)
这是一个概念验证示例:
var data = { accounts: [{
id: 1,
account_id: 1,
debit: 1000
},
{
id: 2,
account_id: 5,
credit: 1500
},
{
id: 3,
account_id: 8,
debit: 500
}
]};
var debitSum = _.reduce(data.accounts, function(sum, account) {
return (account.debit || 0) + sum;
}, 0);
var creditSum = _.reduce(data.accounts, function(sum, account) {
return (account.credit || 0) + sum;
}, 0);
console.log('Debit: ' + debitSum + '; Credit: ' + creditSum);
if (debitSum !== creditSum) {
console.log('Debit and credit are not equal!');
} else {
console.log('All ok');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;