【问题标题】:Laravel Date Mutator With Joins带有连接的 Laravel 日期修改器
【发布时间】:2018-04-12 20:19:39
【问题描述】:

我已经为我的 Schedules 表中的“日期”字段设置了一个 mutator。当我使用它的模型直接从中获取数据时,一切正常。

但是,当我将 Schedules 表连接到查询中的另一个表时,我将如何更改“日期”字段?

示例:我正在对我的 GameRequests 表运行查询并将 Schedules 表加入其中,但日期字段未发生变化。它仍然是“YYYY-MM-DD”格式。

调度模型中的我的 Mutator:

/**
 * Always format date to Month / Day / Year when retrieving.
 */
public function getDateAttribute($value) {
    return date('M d, Y', strtotime($value));
}

以下工作完美:

$list = Schedule::where('team_id', $id)->orderBy('date')->get();

return $list->toJson();

以下不是因为我没有调用调度模型:

$list = GameRequest::whereIn('team_to', $user_teams)
        ->join('teams as team_to', 'game_requests.team_to', '=', 'team_to.id')
        ->join('teams as team_from', 'game_requests.team_from', '=', 'team_from.id')
        ->join('schedules', 'game_requests.schedule_id', '=', 'schedules.id')
        ->select(
            'game_requests.id as gr_id',
            'game_requests.team_to',
            'game_requests.team_from',
            'team_to.display_name as to_name',
            'team_from.display_name as from_name',
            'schedules.date'
        )
        ->orderBy('date')
        ->get();

    return $list->toJson();

【问题讨论】:

  • 你做了什么?
  • 刚刚更新了我原来的帖子。

标签: laravel date join eloquent format


【解决方案1】:

您可以使用 MySQL 的 DATE_FORMAT 函数和 selectRaw 来获取所需格式的日期。

$list = GameRequest::whereIn('team_to', $user_teams)
    ->join('teams as team_to', 'game_requests.team_to', '=', 'team_to.id')
    ->join('teams as team_from', 'game_requests.team_from', '=', 'team_from.id')
    ->join('schedules', 'game_requests.schedule_id', '=', 'schedules.id')
    ->selectRaw(
        'game_requests.id as gr_id',
        'game_requests.team_to',
        'game_requests.team_from',
        'team_to.display_name as to_name',
        'team_from.display_name as from_name',
        'DATE_FORMAT(schedules.date,'%b %d, %Y') as date'
    )
    ->orderBy('date')
    ->get();

return $list->toJson();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    相关资源
    最近更新 更多