【问题标题】:how to match a certain value inside an array using eloquent laravel 5.8?如何使用 eloquent laravel 5.8 匹配数组中的某个值?
【发布时间】:2019-04-28 09:47:39
【问题描述】:

在验证中,我没有将产品字段名称设置为唯一,但希望它在某些方面是唯一的,例如具有相同 user_id 的产品,我希望单个用户具有唯一的产品名称。一些代码也将产品字段名称的值与数据库中的产品名称数组匹配。

    $products = Product::find(auth()->user()->id)->get();

    foreach ($products as $product) {
        $pro_name = $product->name;
    }

    $value = Input::get('name');

    if ($value == anyOf($pro_name) {
        return false;
    }

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    我假设 user_id 不是您产品表的主键。所以你不能使用查找。这样做:

    $products = Product::where(user_id, auth()->user()->id)->get();
    

    您需要一个产品名称数组。像这样得到它:

    $pro_name = Product::where(user_id, auth()->user()->id)->pluck('name')->toArray();
    

    检查数组是否有某个键使用:

    if (in_array($value, $pro_name)) {
        return false;
    }
    

    你也可以这样做:

    $value = Input::get('name');
    
    $product = Product::where(user_id, auth()->user()->id)->where('name', $value)->first();
    
    if ($product){
    return false;
    }
    

    【讨论】:

    • 这就是我要找的。非常感谢
    【解决方案2】:

    也可以使用标准的 Laravel 验证来定义这个验证:

        $this->validate(
            $request,
            [
                'name' => \Illuminate\Validation\Rule::unique('products', 'name')
                    ->ignore($id) // id of product being updated. If it is a new product you can remove this, or pass null
                    ->where(function ($query) {
                        return $query->where('user_id', \Auth::user()->id);
                    })
            ]
        );
    

    【讨论】:

    • 谢谢它,但对我的要求没有帮助,有助于更新记录。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 2020-01-20
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多