dtry54612 2017-02-22 06:12
浏览 278

Laravel Eloquent可空字段值转换为字符串“NULL”

I have in my model a query to get data from the database and there are nullable fields present in my database table. When I try to display all the records in my view, the fields which are of null value, is displayed as "NULL". I want these values to be display as just empty string.

Here is what I have in my controller:

public function showDetails($action, $id)
{
        $data_model= new PersonData();
        $persons= $data_model->loadSpecificPerson($id);

        return view('pages.admin.reporting_person_details', ['action' => $action, 'id' => $id])->with('id', $id)->with(compact('persons'));
}

In my model:

public function loadSpecificPerson($id)
{
        $persons = DB::select("SELECT * FROM complainant_t WHERE ComplainantID = ?", [$id]);
        return $persons;
}

I wanted to do it like how you would do it in an array:

foreach($array as $key => $value)
{
   if($array[$key] == NULL)
   {
        $array[$key] = "";
   }
}

This isn't possible to use with $persons since it's an object and must be accessed with name right? So how should I perform this without having to access it by the column names?

  • 写回答

3条回答 默认 最新

  • douyanning3724 2017-02-22 06:19
    关注

    Basically NULL field is always displayed '' empty string. But if not then you can achieve as below.

    foreach($persons as $person){
        //consider you want to display here
        //Please check it's NULL or 'NULL'
        echo $person->field === NULL ? '' : $person->field;
    }
    

    Here basically it will check all fields, If field is NULL then it will display '' empty string else it will display original value.

    Hope it helps you!

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向