我不太确定是否允许在这里要求代码审查,但我会尝试代码改进。
好的,我刚开始使用Laravel 4,我阅读了一些关于如何在laravel中实现CRUD的教程。最后我能够开发出一部分。我要向您展示的更多是关于Controller和Eloquent ORM。
我这里有2个模型“组”,只能有一个“国家”,但“国家”可以分配到不同的“组”(“一对多”)
class Group extends Eloquent
{
protected $table = 'group';
protected $guarded = array('group_id');
protected $primaryKey = 'group_id';
public function country()
{
return $this->belongsTo('country', 'country_id');
}
}
class Country extends Eloquent
{
protected $table = 'country';
protected $primaryKey = 'country_id';
public function group() {
return $this->hasMany('group', 'country_id');
}
}
在我的控制器中,我有index()函数,它接受用户搜索过滤器和分页请求。
public function index()
{
// search variables here
$s_name = Input::get("s_name");
$s_status = Input::get("s_status");
// order variables here
$sortBy = Input::get("sort_by");
$orderBy = Input::get("order_by");
// get all the groups
$groups = Group::with('country')
->join('country', 'country.country_id', '=', 'group.country_id');
// search conditions
$groups = $groups->whereIn('group_status', array(ACTIVE, INACTIVE));
if (!empty($s_name)) {
$groups = $groups->where('group_name', 'LIKE', "%$s_name%");
}
if (!empty($s_status)) {
$groups = $groups->where('group_status', 'LIKE', "%$s_status%");
}
// order
if (!empty($sortBy)) {
$orderBy = (empty($orderBy)) ? ASCENDING : $orderBy;
if ($sortBy == "o_name") {
$groups = $groups->orderBy('group_name', $orderBy);
} else if ($sortBy == "o_country") {
$groups = $groups->orderBy('country_short_name', $orderBy);
} else if ($sortBy == "o_status") {
$groups = $groups->orderBy('group_status', $orderBy);
}
} else {
$groups = $groups->orderBy('group.created_at', DESCENDING);
}
$groups = $groups->paginate(PAGINATION_LIMIT);
}
希望有健康的回应家伙。 提前谢谢!