Justin's Words

Laravel 常见需求解决

搜索

SQL:

1
SELECT * FROM  users WHERE (username LIKE '%search%') OR (profession LIKE '%search%') OR (skilled_subject LIKE '%search%') ORDER BY username ASC;

对应的 Eloquent

1
2
3
4
5
6
7
8
9
10
public function search() {
$search = htmlspecialchars(trim(Input::get('search')));
$users = User::where(function ($query) use ($search) {
$query->where('username', 'like', '%'.$search.'%');
$query->orWhere('profession', 'like', '%'.$search.'%');
$query->orWhere('skilled_subject', 'like', '%'.$search.'%');
})->orderBy('username', 'asc')->paginate(20);

return View::make('pages.tutors')->with(array('users' => $users, 'query' => $search));
}

scotch.ioEloquent 有详细讲解。