【问题标题】:Exists validations with multiple tables存在具有多个表的验证
【发布时间】:2020-05-11 10:48:03
【问题描述】:

Laravel 版本 (7.x)。

我有三张桌子companies、complaint_types 和complaints。

投诉与company 相关联。

当complaint 分配给employee 后,只有他/她可以看到并在访问后进入投诉状态。在进入 cmets 之前,必须验证 complaint,否则不允许输入评论,这是在通过名为 complaint_id 的隐藏字段提交表单时处理的。

我已添加此验证,因为我不希望任何人打开检查工具、玩弄这些值并导致应用程序出错。

表格:

companies:  ->  complaint_types:  ->  complaints:
|-- id          |-- id                |-- id
|-- ...         |-- company_id        |-- complaint_type_id
                |-- ...               |-- ...

投诉.php:

public function complaintType()
{
    return $this->belongsTo(ComplaintType::class);
}

ComplaintType.php:

public function company()
{
    return $this->belongsTo(Company::class);
}

public function complaints()
{
    return $this->hasMany(Complaint::class);
}

ComplaintController.php:

private function validate($data)
{
    # variables
    $rules = [
        'complaint_id' => [
            'required', 
            'exists:complaints,id,complaintType.company_id,' . session()->get('COMPANY')
        ],

        -- OR --

        'complaint_id' => [
            'required', 
            'exists:complaints,id,complaint_types.company_id,' . session()->get('COMPANY')
        ],

        ...
    ];

    $messages = [
        'complaint_id.required' => '`Complaint` - Required<br>',
        'complaint_id.exists'   => '`Complaint` could not be identifed<br>',

         ...
    ];

    return Validator::make($data, $rules, $messages);
}

错误
Column not found: 1054 Unknown column 'complaintType.company_id' in 'where clause' (SQL: SELECT COUNT(*) as aggregate FROM complaints WHERE id = 3 AND complaintType.company_id = 1)

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    问题解决了,这是我的代码:

    $rules = [
        'complaint_id' => [
        'required',
        function($attribute, $value, $fail) use ($data) {
            $Complaint = Complaint::where('id', $value)
                ->whereHas('complaintType', function($query) use($data) {
                    return $query->where('company_id', session()->get('COMPANY'));
                })->count();
    
            if($Complaint <= 0)
                $fail('`Complaint` could not be identified');
        }
    ],
    

    我在这里找到了参考How can I add a join to a custom exists rule for a laravel validator?

    【讨论】:

      【解决方案2】:

      您应该指定与主键的关系,例如:

      public function complaints(){
      return $this->hasMany(Complaint::class, 'complaint_type_id','id');
      }
      

      【讨论】:

        猜你喜欢
        • 2020-04-05
        • 2018-02-18
        • 1970-01-01
        • 2014-07-06
        • 1970-01-01
        • 2021-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多