laravel collection 的问题

今天在使用laravel的时候碰到个问题,我在模型里面使用了修改器,把type对应的数字变成了显示的中文,像下面这样:

public function getTypeAttribute($value)
{
 $labelType = [
    1 => '个性',
    2 => '风格',
    3 => '用户评论标签',
 ];
 return $labelType[$value]??'';
}

然后再使用collection进行筛选的时候就出问题了,

public function getLabels($type = 0)
{
    $data = Label::where('status', 1)->get();
    $need = (object) [];
    if ($type == 1) {
        $need->character = $data->where('type', 1);
        $need->style = $data->where('type', 2);
        $need->customer_give_label = $data->where('type', 3);
        return $need;
    }
    return $data;
}

结果发现$need取不到值,让我一伙的不是这里,二是我在这里打印$data的时候里面的不论是attributes还是original里面的type都还显示的是数字!这个就有点匪夷所思了。

然后我就想到了要去
D:\phpStudy\WWW\xxx\vendor\laravel\framework\src\Illuminate\Support\Collection.php
直接查看 construct ,可以看到,

public function __construct($items = [])
{
    $this->items = $this->getArrayableItems($items);
}

猜你喜欢

转载自blog.csdn.net/zhezhebie/article/details/80596047