这是我在 Controller 中的编辑功能
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;
}
}
Controller
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', compact('game', 'team', 'competition'));
}
关于php - 如何压缩此代码以从 Laravel Controller 向 View 发送信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31259245/