这是我在控制器中的编辑功能
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 Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; class Competition extends Model { protected $appends = ['fullname']; ... public function getFullnameAttribute() { return $this->name.' '.$this->venue; } }
球队
<?PHP namespace App; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; 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')); }