对另一个列条目的重复条目的限制

时间:2019-04-28 07:32:57

标签: database laravel eloquent criteria

我有两个带有

的模型MemberSaving
Member('id','name')
Saving('id','member_id','amount','month')

我必须限制给定月份重复保存会员。

Member.php

class Member extends Model
{
protected $fillable=['name','address','phone']; 
public function loan()
{
    return $this->hasOne(Loan::class,'member_id','id');
}
public  function savings()
{
    return $this->hasMany(Saving::class,'member_id','id');
}
}

Saving.php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Saving extends Model
{
protected $fillable=['amount','month','member_id']; 
 public function member()
{
    return $this->belongsTo('App\Member','member_id','id');
} 
}

是否可以使用模型中的函数或控制器来实现限制? 编辑: 这就是我尝试过的方式。 SavingController.php

    public function addSaving(Request $request){
    if($request->isMethod('get')){
        $memberData = Member::all();
        return view($this->_pagePath.'saving.addsaving',compact('memberData')); 
        //return redirect()->back();
    }
    if($request->isMethod('post')){
        $this->validate($request,[
            'amount' => 'required',
            'month' => 'required'
        ]);
        $data['amount'] = $request->amount;
        $data['month'] = $request->month;
        $data['member_id']= $request->name;
        $member= Member::find(1);
        if($member->savings()->where('month',$request->month)->exists())
        {
          return 'Savings for this month are already added.';
        }
        else
        {
        if(DB::table('savings')->insert($data)){
            return redirect()->route('saving')->with('success','data was successfuly inserted');
        }
    }
                }
 }

1 个答案:

答案 0 :(得分:1)

枚举是我朋友月份的错误列,除非您不关心年份。因为这样,您将只能存储每月的储蓄,而不能分别存储每年的储蓄。

您的关系设置正确,因此您可以进行如下检查:

// considering you have the specific member selected
$member = Member::find('ID_OF_THE_MEMBER');
if($member->savings()->where('month', APRIL)->exists())
{
    return 'Savings for this month are already added.';
}