【问题标题】:Adding custom column to Eloquent query result (Laravel)将自定义列添加到 Eloquent 查询结果(Laravel)
【发布时间】:2020-10-18 06:31:38
【问题描述】:

我从我的数据库中得到一个集合

$events = DB::table('events')
  ->select('id', 'eventId', 'resourceId', 'title', 'start', 'end')
  ->get();

并想添加一个字段color,以便我可以根据字段title 的值设置颜色值。我的方法不起作用,echoput 给出了错误。

$events->put('color', 'blue');
$events->each(function($item, $key){
  if($item == 'Garage')
    echo $item;
});

【问题讨论】:

  • 那是query builder,而不是Eloquent。如果你使用 Eloquent,你可以创建一个 accessor
  • 这不是一个雄辩的查询,而是使用查询生成器的查询。如果它是一个雄辩的查询,您将直接使用 Event 模型,您可以将 color 添加到 visible 数组并在模型上定义一个 getColorAttribute 函数:laravel.com/docs/7.x/eloquent-mutators#defining-an-accessor 你看到了什么单词 5?跨度>
  • 我知道我可以使用访问器来访问已经存在的列。但我还需要将color 列添加到数据库中不存在的集合中。

标签: laravel foreach eloquent


【解决方案1】:

首先使用Eloquent 方法。

$events = Event::query()
    ->select('id', 'eventId', 'resourceId', 'title', 'start', 'end')
    ->get();

在您的 Event 模型上,添加 Eloquent accessor

class Event extends Model
{
    public function getColorAttribute($value)
    {
        if ($this->title === 'Garage') {
            return 'blue';
        }

        return 'unknown';
    }
}

现在您可以附加它进行转换或直接访问它。

class Event extends Model
{
     protected $appends = ['color'];
}

$event->color;

【讨论】:

  • 谢谢你,我真的从这个例子中学到了很多。
猜你喜欢
  • 2015-01-15
  • 2016-04-04
  • 2015-01-24
  • 1970-01-01
  • 2020-09-24
  • 2018-10-22
  • 2020-03-22
  • 2021-10-26
  • 2019-12-24
相关资源
最近更新 更多