php – 如何压缩此代码以便从Laravel Controller向视图发送信息
发布时间:2020-12-14 19:42:26 所属栏目:大数据 来源:网络整理
导读:这是我在控制器中的编辑功能 public function edit($id){ $game = Game::find($id); // build list of team names and ids $allTeams = Team::all(); $team = []; foreach ($allTeams as $t) $team[$t-id] = $t-name(); // build a list of competitions $al
这是我在控制器中的编辑功能
public function edit($id) { $game = Game::find($id); // build list of team names and ids $allTeams = Team::all(); $team = []; foreach ($allTeams as $t) $team[$t->id] = $t->name(); // build a list of competitions $allCompetitions = Competition::all(); $competition = []; foreach ($allCompetitions as $c) $competition[$c->id] = $c->fullname(); return View::make('games.edit',compact('game','team','competition')); } 我正在发送数据,以便在选择列表中显示.我知道Eloquent ORM方法列表,但问题是我知道它只能将属性名称作为参数,而不是方法(如name()和fullname()). 我怎样才能优化这一点,我还能使用Eloquent吗? 解决方法
我会调查
attributes and appends .你可以通过调整模型来做你想做的事.
竞争 <?php namespace App; use IlluminateDatabaseEloquentCollection; use IlluminateDatabaseEloquentModel; class Competition extends Model { protected $appends = ['fullname']; ... public function getFullnameAttribute() { return $this->name.' '.$this->venue; } } 球队 <?php namespace App; use IlluminateDatabaseEloquentCollection; use IlluminateDatabaseEloquentModel; class Team extends Model { protected $appends = ['name']; ... public function getNameAttribute() { return $this->city.' '.$this->teamName; } } 调节器 public function edit($id) { $game = Game::find($id); $team = Team::get()->lists('id','name'); $competition = Competition::get()->lists('id','fullname'); return View::make('games.edit','competition')); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |