Laravel在模型检索时添加额外的日期数组

huangapple go评论52阅读模式
英文:

Laravel add additional array of dates while model retrieving

问题

我有一个用户和考勤之间的关系,在考勤表中我有字段 startend,它们都是 date 类型的字段。我能够通过关系检索数据。我正在获取用户在当前月份的缺席记录,然后我想向用户模型添加一个名为 "additional" 的字段/变量/属性,其中包含这些日期(解析为 Carbon 对象)。这种操作是否可行?

我尝试使用 booted() 方法和 static::retrieved 函数,在其中调用另一个函数。

当我需要在视图中检查这些缺席记录以显示日历时,我需要多次迭代(之前我在用户模型内创建了一个方法来检索和解析这些数据)。

我希望实现类似于以下的功能:

if (in_array($someDates, $user->additional_array)) [...]

之前我使用以下代码:

if (in_array($someDates, $user->methodToReturnAdditionalArray())) [...]

有什么建议吗?

英文:

I have relationship between User and Attendance, where in Attendance table I have field start and end which are date fields. I'm able to retrieve the data through relationship. I'm getting User Absences for current month and afterwards I want to add "additional" field/variable/attribute with array of this dates(parsed to Carbon) to User model. Is it possible?

I was trying to use booted() method with static::retrieved function, where I call another.

When I need to check those absences in view to display a Calendar I iterate too many times (previously I've created a method inside Users model to retrieve and parse those data).

I need to achieve something like this:

if(in_array($someDates, $user->additional_array)) [...]

Previously I've got:

if(in_array($someDates, $user->methodToReturnAdditionalArray())) [...]

Any idea?

答案1

得分: 1

你可以使用Laravel属性,并定义获取所需数据的新方法。

示例:

public function getAdditionalArrayAttribute()
{
    // 返回你想要的数组项目列表;
}

然后你可以像这样使用它:

$model->additional_array;
英文:

You can use the Laravel Attributes and define the new method for getting the data you want

Example:

public function getAdditionalArrayAttribute()
{
    // return the list of array items you want;
}

And then you can use it like here:

$model->additional_array;

huangapple
  • 本文由 发表于 2023年2月14日 19:48:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定