如何用雄辩的方式检索数据 [英] How to retrieve data with zeros in eloquent

查看:133
本文介绍了如何用雄辩的方式检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从数据库检索多个数据创建学生编号。



喜欢 Course_ID.Year_Code.Student_no



为了检索相同的数字号码我填写我的原始学生编号(创建时给出)为0001,0002。



当我尝试通过从数据库获取该号码来检索学生编号



我得到的结果没有零。



让我们说 Course_ID 22 Year_Code 16



Student_NO 0005



我返回号码为 22165 ,应该是 22160005
这是我如何获得学生。

  $ students = \App\Student :: with('payment') - > where('branch' $ ID) - >获得(); 

(我实际上收到student_no没有零,查询如下)



这是我写的刀片

 < td> {{$ student-> Course_ID $ student-> course-> year_code。$ student-> student_no}}< / td> 

PS:我知道如何使用str_pad检索本机php的数字。请问是否有一种方法可以在雄辩中做到。

解决方案

没有直接的方法那个雄辩会提供,所以你需要自己添加一些逻辑。



一个选项是将 student_no 存储为数据库中的字符串否则,当以PHP为单位获取整数时,零将会丢失,因为PHP不关心您的 ZEROFILL 并将 0005 视为 5



另一个选项是在从数据库中获取数据后,在PHP中手动附加零,例如通过在模型中添加一个访问器:

  public function getStudentNoAttribute(){
return sprintf(%05d $这 - >属性[ 'student_no']);
}

这样,只要访问 student_no 属性您的模型将自动转换为零填充字符串。


I am creating a student number from retrieving multiple data from database.

Like Course_ID.Year_Code.Student_no

In order to retrieve same digit numbers I fill my raw student number (which is given on creation) as 0001, 0002.

When I try to retrieve my student number by getting this number from database

I get results without zeros.

Lets say Course_ID 22 and Year_Code 16

and Student_NO 0005

I return number as 22165 which should be 22160005. this is how I get students.

$students = \App\Student::with('payment')->where('branch', $id)->get();

(I actually recieve student_no without zeros with the query below)

and this is how I write in blade

<td>{{$student->Course_ID.$student->course->year_code.$student->student_no}}  </td>

PS: I do know how to retrieve numbers with native php by using str_pad. I ask if there is a method to do it on Eloquent.

解决方案

There is no straightforward way to do that that Eloquent would offer so you'd need to add some logic yourself.

One option would be to store student_no as a string in the database, otherwise zeros will be lost when it's fetched as an integer in PHP, as PHP doesn't care about your ZEROFILL and treats 0005 as 5.

Another option is to append zeros manually in PHP after fetching data from the database, e.g. by adding an accessor in your model:

public function getStudentNoAttribute() {
  return sprintf("%05d", $this->attributes['student_no']);
}

This way, whenever you access student_no attribute of your model it would be converted to zero-filled string automatically.

这篇关于如何用雄辩的方式检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆