You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

根据数据库foo_options字段值返回对应SVG的问题求助

Fix: Always Returning Green SVG Instead of Red

Let's break down the two key issues causing your code to always return the green SVG, even when foo_options is 3:

1. The Accessor Isn't Checking the Actual foo_options Value

Your getOptionValueAttribute method is checking literal strings like '1' instead of the actual value of the foo_options field. In PHP, any non-empty string evaluates to true, so the first if ('1') condition will always pass—no matter what the real foo_options value is.

Fixed Model Accessor Code

public function getOptionValueAttribute(){
    // Grab the actual value of your foo_options field from the model
    $optionValue = $this->foo_options;
    
    if ($optionValue === '1') {
        return '<svg>Green</svg>';
    } elseif ($optionValue === '2') {
        return '<svg>Orange</svg>';
    } elseif ($optionValue === '3') {
        return '<svg>Red</svg>';
    } else {
        return '';
    }
}

We use $this->foo_options to reference the model's actual field value, and strict comparison (===) ensures we match both value and type to avoid unexpected matches.

2. Business Logic Uses Assignment Instead of Comparison

In your conditional check, you're using the assignment operator (=) instead of a comparison operator (== or ===). This means you're setting some_options to '1' every time the code runs, then evaluating that assignment result (which is always '1', a truthy value).

Fixed Business Logic Code

Option 1 (cleaner with in_array):

$validOptionValues = ['1', '2', '3'];
if (in_array($bar->barDetail->some_options, $validOptionValues, true)) {
    dd($bar->barDetail->optionValue);
}

The third true parameter in in_array enables strict type checking, just like ===.

Option 2 (explicit comparisons):

if($bar->barDetail->some_options === '1' || $bar->barDetail->some_options === '2' || $bar->barDetail->some_options === '3') {
    dd($bar->barDetail->optionValue);
}

With these fixes, when foo_options is 3, your accessor will correctly return the red SVG.

内容的提问来源于stack exchange,提问作者daugaard47

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 07:08:14