检查所有模型属性是否已填充

huangapple go评论57阅读模式
英文:

Check if all model attributes are filled

问题

你好,我明白你不需要代码部分的翻译。以下是翻译好的部分:

  • 你有一个用于用户的additionalInfo的模型,所以如果用户填写了这些额外信息,他们将获得奖励,所以我需要检查是否所有additionalInfo的值都已填写。我的问题是,我是否需要逐个检查每个值?我的意思是是否需要像这样逐个检查每个属性,使用$clientAdditionalInfo['address'],然后检查下一个$clientAdditionalInfo['city'],然后$clientAdditionalInfo['province']等等...

或者我应该像这样做:

public function isCompleted() {
    $user = auth()->user();

    $clientAdditionalInfo = $user->client->additionalClientInfo->where('client_id', $user->client->id)->get()->first();

    if ($clientAdditionalInfo) {
        $attributes = $clientAdditionalInfo->getAttributes();

        foreach ($attributes as $attribute) {
            // 在这里,我可以检查每个属性是否都已填写?
        }
    }
}

尝试逐个属性进行迭代,也许我应该逐个属性检查是否isset,然后如果所有都已设置,是否就是所有additionalInfo都已设置并且可以奖励。但是,一旦所有属性都已设置,我如何检查是否所有属性都已设置?

我看到,当我循环属性时,有一个最后一个值是null(在updated_at之后),但在数据库中没有更多值,这可能是foreach的问题吗?数据库中只有一行,填写了所有值,如果我在foreach中执行dump($key)dump($attribute),我会得到以下结果:

^ "id"
^ 1
^ "address"
^ "Calle test 123"
^ "city"
^ "Barcelona"
^ "province"
^ "Barcelona"
^ "postal_code"
^ "08010"
^ "web"
^ "https://www.test.com"
^ "phone"
^ "123456789"
^ "activity"
^ "Social"
^ "number_of_employees"
^ 150
^ "interest"
^ "Test"
^ "client_id"
^ 8
^ "created_at"
^ "2023-02-08 10:48:56"
^ "updated_at"
^ "2023-02-08 11:53:43"
^ null

我不知道这个null是从哪里来的,它不应该...

好的,我的错误,我检查得不好,我应该从$request->all()中检查。这样,我可以只检查值,而不包括created_atupdated_at,这样我可以更具体地进行检查。

希望这能帮助你理解你的代码问题。如果有其他疑问,请随时提出。

英文:

Hello I've a model that is additionalInfo for a user, so if the user fills this additional info it will get a reward, so I'll need to check if all values from this additional info is filled. My question is, do I need to check it per every value? I mean do I need to check it like this per attribute using $clientAdditionalInfo\['adress'\] then I will check the next $clientAdditionalInfo\['city'\] then $clientAdditionalInfo\['province'\] etc...

Or should I do something like this.

public function isCompleted() {
    $user = auth()->user();
    
            $clientAdditionalInfo = $user->client->additionalClientInfo->where('client_id', $user->client->id)->get()->first();
    
    if($clientAdditionalInfo){
                $attributes = $clientAdditionalInfo->getAttributes();
    
                foreach($attributes as $attribute) {
                    // HERE I COULD CHECK IF EVERY ATTRIBUTE IS FILLED?
                }
            }
}

Tried iterating per attribute and maybe I should check per attribute if isset and then if all are set is that all additionalInfo is set and give the reward. But once all attributes are set how can I check that ALL attributes are set?

What I'm seeing if when I loopon the attributes, there's a last value which is null (after the updated_at) but on the database there's no more values after the database, it could be a thing of the foreach? There's only one row on the database and filled all the values, if I dump($key) & dump($attribute) on the foreach I get the following:

^ "id"
^ 1
^ "address"
^ "Calle test 123"
^ "city"
^ "Barcelona"
^ "province"
^ "Barcelona"
^ "postal_code"
^ "08010"
^ "web"
^ "https://www.test.com"
^ "phone"
^ "123456789"
^ "activity"
^ "Social"
^ "number_of_employees"
^ 150
^ "interest"
^ "Test"
^ "client_id"
^ 8
^ "created_at"
^ "2023-02-08 10:48:56"
^ "updated_at"
^ "2023-02-08 11:53:43"
^ null

I dont know where this null is coming from, it shouldn't...

Okay my bad, I was checking it badm I should check it from $request->all(). This way I'll be able to check just the values without the created_at & updated_at so I can be more specific and check it better.

答案1

得分: 1

以下是翻译好的内容,代码部分未翻译:

最简单的方法是使用您在问题中建议的循环:

$attributes = $clientAdditionalInfo->getAttributes();
foreach ($attributes as $key => $value) {
    // 检查属性是否被正确设置
}

然而,这并不总是容易的。有时您对属性有一个默认值,该值不是 null,而且被设置为默认值。例如,您可能会有像 ‘NOTSET’‘UNINITIALIZED’‘INITIALIZED’‘FINALIZED’ 这样的值。在这种情况下,您需要检查值是否是 ‘NOTSET’。此外,您的属性可能默认为0,而适当的值是严格正数(例如价格)。因此,您可能需要进一步的函数/条件来评估可能存在的不同类型的属性。

此外,有可能某处有一个 null 值,但它完全正常并被正确初始化。例如,生死日期未知,即对于目前仍然活着的人,值为 null

此外,有可能您有一个复合属性,例如某些物品是物品数组,每个物品都有自己的属性,这种情况下,您需要对它们进行循环,因此实现一个可迭代集合的函数是有道理的,比如数组或 StdClass 对象。

最后,您可能有一些需要特别评估的对象实例作为附加信息的属性。例如,如果健康状态是附加信息的一部分,健康状态可能是一个独立的对象。

您可以使用 json_encode 对这些对象进行编码,然后使用 json_decode 转换为数组,并将其处理为属性数组(嵌套或非嵌套)进行评估。或者,您可以为您的类创建一个预期属性数组,然后进行循环。后一种方法的优势是,如果您愿意,允许某些属性未初始化,但缺点是您需要关注并可能进行调整。您还可以半自动地在每次构建/部署时跟踪新属性,并假定新属性是必需的。

但是,回到最简单的方法,它看起来像这样:

foreach ($attributes as $attribute) {
    if ((!isset($yourObject->{$attribute}))) {
        return false; //某些属性未初始化
    }
}
return true; //在循环检查了所有内容并发现所有内容都被正确初始化后,返回 true

上述代码没有经过测试,根据您的对象和集合的外观,您可能需要以稍微不同的方式执行它,但思路是循环属性,检查它们是否被正确设置,如果没有,返回 false。一旦检查了所有内容并发现所有内容都被正确初始化,就返回 true。

英文:

The simplest approach is to have a loop like you suggested in the question:

$attributes = $clientAdditionalInfo->getAttributes();
foreach ($attributes as $key => $value) {
    //Check whether the attribute is set properly
}

Yet, this is not always easy. Sometimes you have a default value for an attribute that's not null and which is set as a default. For example, you might have values such as 'NOTSET', 'UNINITIALIZED', 'INITIALIZED', 'FINALIZED'. In such cases you need to check whether the value is 'NOTSET'. Also, your attribute might default to 0 whereas proper values are strictly positive (prices, for example). So, you might have further functions/criterias to evaluate the different kinds of attributes you may have.

Also, it's quite possible that you have a null value somewhere, but it's perfectly fine and properly initialized. For example, a date of death is unknown, i.e. null for people who are currently alive.

Furthermore, it's quite possible that you have a composite attribute, like some items which is an array of items and each item has its own attributes, in which case you will need to loop for them, so it makes sense to implement a function for iterable collections such as arrays or StdClass objects.

Finally, you may have some object instances which need to be specially evaluated as attributes of additional info. For example, if health status is part of additional info, health status might be an object on its own right.

You can json_encode such objects and then json_decode into an array and handle it as an attribute array (nested or not) in your evaluation. Or, you could create an array of expected attributes for your class and loop that. The latter has the advantage of allowing some attributes to be uninitialized if you wish, but, the disadvantage is that you will need to keep an eye on that and possibly adjust it. You can do that semi-automatically as well, by tracking new attributes upon each build/deploy and assume the new attributes to be required.

But, returning to the simplest approach, it looks like this:

foreach ($attributes as $attribute) {
    if ((!isset($yourObject->{$attribute}))) {
        return false; //something was not initialized
    }
}
return true; //we reached this point after looping everything and finding everything being initialized

The above was not tested, you may need to perform it in a slightly different way in your case, depending on how your objects and collections look alike, but the idea is to loop the attributes, see for each of them whether they are properly set, return false if not. Once everything was checked and found to be initialized properly, return true.

答案2

得分: 1

使用array_filter函数

if(!array_diff($attributes, array_filter($attributes))) {
   echo '所有属性都已填充';
}

如果没有提供回调函数,则将删除数组中所有等于FALSE的条目。

英文:

Use array_filter

if(!array_diff($attributes, array_filter($attributes))) {
   echo 'All attributes are filled';
}

If no callback is supplied, all entries of array equal to FALSE deleted.

huangapple
  • 本文由 发表于 2023年2月8日 19:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385052.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定