查询中的手动功能?

Manual function inside query?

有没有办法在 Laravel 中的查询中放入手动函数。

我已将时间戳保存在数据库中的字符串中。我想将时间戳从一个时区转换为另一个时区。所有时间戳都插入一个时区,根据我的用户,我获取时间戳并将其转换为他们的时区。

我想实现的是这样的..

$query = BlogCategory::select('merchant_id', userTime(added_at))              
                        ->where('site_id', $site_id)
                        ->get();

userTime() 函数接受两个参数,时间戳和时区,并将时间戳转换为用户的时间。

我想在获取数据之前使用 userTime() 函数。我不想先获取数据然后执行 foreach 等等。

我知道我可能绝对荒谬,但是 Laravel 中有这种东西吗?

好吧,你可以使用 collection map

$query = BlogCategory::select('merchant_id', 'added_at')              
                        ->where('site_id', $site_id)
                        ->get();

$dateAdded = $query->map(function ($data) {
    // try this if error $data['merchant_id']
    return array(
       'merchant_id' => $data->merchant_id,
       'added_at' => $this->userTime($data->added_at)
   );
})

dd($dateAdded);

在此处阅读 Collection 文档:https://laravel.com/docs/5.8/collections

如果您不想遍历结果集,您应该使用 selectRaw 语句并让您的数据库为您执行此逻辑。

例如,如果您的基础数据库是 MySQL,您可以使用 CONVERT_TIMEZONE 函数并执行类似的操作。

BlogCategory::selectRaw('merchant_id, CONVERT_TZ(added_at, "GMT", "MET") as added_at')              
                    ->where('site_id', $site_id)
                    ->get();