Rom*_*ome 2 foreach laravel eloquent
我从我的数据库中获取了一个集合
$events = DB::table('events')
->select('id', 'eventId', 'resourceId', 'title', 'start', 'end')
->get();
Run Code Online (Sandbox Code Playgroud)
并想添加一个字段,color以便我可以根据该字段的值设置颜色值title。我的方法不起作用,echo并put给出了错误。
$events->put('color', 'blue');
$events->each(function($item, $key){
if($item == 'Garage')
echo $item;
});
Run Code Online (Sandbox Code Playgroud)
首先使用一种Eloquent方法。
$events = Event::query()
->select('id', 'eventId', 'resourceId', 'title', 'start', 'end')
->get();
Run Code Online (Sandbox Code Playgroud)
在您的 Event 模型上,添加一个 Eloquent访问器。
class Event extends Model
{
public function getColorAttribute($value)
{
if ($this->title === 'Garage') {
return 'blue';
}
return 'unknown';
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以附加它以进行转换或直接访问它。
class Event extends Model
{
protected $appends = ['color'];
}
$event->color;
Run Code Online (Sandbox Code Playgroud)