加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – 从Laravel中的db模型中获取所有字段

发布时间:2020-12-14 19:35:56 所属栏目:大数据 来源:网络整理
导读:在创建模型之后,当我尝试获取其属性时,我只获得数据库中填充的字段. ----------------------------------------------DB: | id | shopID | name | bottleID | capacity | ---------------------------------------------- | 1 | 8 | Cola | 3 | | ----------
在创建模型之后,当我尝试获取其属性时,我只获得数据库中填充的字段.

----------------------------------------------
DB: | id | shopID | name | bottleID | capacity |
    ----------------------------------------------
    | 1  | 8      | Cola |  3       |          |
    ----------------------------------------------

在这种情况下,我也需要容量属性,作为空字符串

public function getDrinkData(Request $request)
{
    $drink = Drink::where('shopId',$request->session()->get('shopId'))->first();

    if($drink) {
        $drink = $drink->attributesToArray();
    }
    else {
        $drink = Drink::firstOrNew(['shopId' => $request->session()->get('shopId')]);
        $drink = $drink->attributesToArray(); // i want to get even empty fields
    }
    return view('shop.drink')->(['drink' => $drink])
}

但是为了以后的使用(在视图中),我需要拥有所有属性,包括空属性.我知道这段代码可以正常工作,但我不知道如何更改它以检测所有属性.

解决方法

您可以使用Schema :: getColumnListing($tableName)来获取表中所有列的数组.使用该信息,您可以创建一个基本数组,其中所有列名称都是键,所有值都为null,然后合并Drink对象的值.

public function getDrinkData(Request $request)
{
    $drink = Drink::where('shopId',$request->session()->get('shopId'))->first();

    if($drink) {
        $drink = $drink->attributesToArray();
    }
    else {
        $drink = Drink::firstOrNew(['shopId' => $request->session()->get('shopId')]);

        // get the column names for the table
        $columns = Schema::getColumnListing($drink->getTable());
        // create array where column names are keys,and values are null
        $columns = array_fill_keys($columns,null);

        // merge the populated values into the base array
        $drink = array_merge($columns,$drink->attributesToArray());
    }
    return view('shop.drink')->(['drink' => $drink])
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读