2013-06-21 5 views
0

Laravel 웅변 ORM 대다 직원의 목록을 표시하는 검색 양식 나는 웅변으로, Laravel의 V3를 사용하고 검색 쿼리

내가 직원 데이터베이스가이 응용 프로그램에 대한 MySQL 데이터베이스, 검색 기준과 일치하는 하나 이상의 필드를 채울 수 있으며 채워진 모든 필드에서만 일치합니다. 아래 보이는 것처럼 : http://i.stack.imgur.com/Ttfhr.png

"Training"에 대한 multiselect를 추가 한 것 외에는 모든 기능이 올바르게 검색됩니다. 직원은 0에서 많은 교육 인증서를 첨부 할 수 있습니다. 사용자가 "Matt"라는 이름을 검색하고 교육 검색 기준에 따라 "CSTS"를 확인하면 목록에 Matt과 비슷한 이름을 가진 모든 직원이 표시되고 CSTS 교육도 받게됩니다. 다음과 같이

데이터베이스 스키마는 다음과 같습니다

user 
--id 
--first_name 
--last_name 
--job_title_id 
etc... 


training 
--id 
--name 
--issused_date 
--expiry_date 

user_training 
--id 
--user_id 
--training_id 

모델의 사용자 및 교육을위한 다음과 같다 :

class User extends Eloquent { 

    public static $table = 'user'; 

    public function training(){ 
    return $this->has_many_and_belongs_to('training','user_training'); 
    } 


class Training extends Eloquent { 

    public static $table = 'training'; 


    public function users(){ 
     return $this->has_many_and_belongs_to('user','user_training'); 
    } 



} 

을 내가 가지고있는 다음 코드, 함수 검색, 제가 재판을위한 교육 :

Route::post('(:bundle)/list', function() { 

$search = new StdClass(); 
$search->first_name = Input::get('first_name'); 
$search->last_name = Input::get('last_name'); 
$search->job_titles = Input::get('job_titles'); // array of ids/returns null if none selected 
$search->training = Input::get('training'); // array of ids/returns null if none selected 
$search->city = Input::get('city'); 
$search->province = Input::get('province'); 
$search->phone = Input::get('phone'); 
$search->status = Input::get('status'); 
$search->gender = Input::get('gender'); 
$search->hire_from_date = Input::get('hire_from_date'); 
$search->hire_to_date = Input::get('hire_to_date'); 
$search->current_location = Input::get('current_location'); 
$search->role = Input::get('role'); 

Session::put('search', $search); // so we can access inside query builder sub-functions 


$query = User::where('active', '=', true); 

if(!empty($search->training)) { // one or many 


    $query = User::with(array('training' => function($query) { 
     $s_search = Session::get('search'); 
     //$query->where_in('training.id', $s_search->training); 
     //foreach($s_search->training as $id) { 
     // $query->where('training.id', '=', $id); 
     //} 
    })); 
} 


//$query = User::join('user_training', 'user.id', '=', 'user_training.user_id'); 
//$query->join('user_training', 'user.id', '=', 'user_training.user_id'); 
//$query->join('training', 'training.id', '=', 'user_training.training_id'); 

if(!empty($search->first_name)) { $query->where('first_name', 'LIKE', '%' . $search->first_name . '%'); } 
if(!empty($search->last_name)) { $query->where('last_name', 'LIKE', '%' . $search->last_name . '%'); } 

if(!empty($search->city)) { $query->where('city', 'LIKE', '%' . $search->city . '%'); } 
if(!empty($search->province)) { $query->where('province_id', '=', $search->province); } 

if(!empty($search->gender)) { $query->where('gender', '=', $search->gender); } 
if(!empty($search->phone)) { $query->where('phone_1', 'LIKE', '%' . $search->phone . '%'); } 

if(!empty($search->status)) { $query->where('status_id', '=', $search->status); } 
if(!empty($search->role)) { $query->where('role_id', '=', $search->role); } 
if(!empty($search->current_location)) { $query->where('location_id', '=', $search->current_location); } 

if(!empty($search->hire_from_date)) // "after" 
    $query->where('hire_date', '>=', date('Y-m-d', strtotime($search->hire_from_date))); 

if(!empty($search->hire_to_date)) // "before" 
    $query->where('hire_date', '<=', date('Y-m-d', strtotime($search->hire_to_date))); 

if(!empty($search->job_titles)) { // one or many 
    $query->where(function($query){ 
     $s_search = Session::get('search'); 
     foreach($s_search->job_titles as $id) { 
      $query->or_where('job_title_id', '=', $id); 
     } 
    }); 
} 



$query->order_by('last_name'); 

$user_list = $query->distinct()->get(); 
$user_count = $query->count(); 

var_dump($user_list); die; 


if(Input::get('action') == 'export') { 

    if(Permission::check("Export Users CSV")) { 
     $now = new DateTime(); 
     return Response::download(User::get_group_csv($user_list), date_format(new DateTime(), 'Y-m-d') . '_User_Export.csv'); 
    } 

} 

"$ user-> training"은 id의 간단한 배열로 나타납니다. Training-> id 표와 일치 함

작업 제목 검색은 multiselect와 함께 올바르게 작동하지만 job_title_id는 관계가 아닌 사용자 테이블에 있습니다.

난 열망하는로드를 사용하여 Eloquent의 "with"를 사용하여 수동으로 결합하여 루프를 시도했지만 모두 성공하지 못했습니다. 누군가 올바른 방향으로 나를 가리킬 수 있습니까?

+0

"누군가 올바른 방향으로 나를 안내 할 수 있습니까?"라는 정보가 많이 있습니다. 그러나 나는 당신이 원하는 것을 이해하지 못합니다. 어떤 방향으로 향하고 싶습니까? – AdrianHHH

+0

마지막 목표는 다중 선택에서 여러 "교육"항목을 선택할 수 있도록하는 것이며 검색을 클릭하면 해당 교육 인증서가있는 사용자 만 반환합니다 – Matt

+0

@Antonio Carlos Ribeiro 도움을 주셔서 감사합니다 – Matt

답변

1

먼저 익명 함수에 변수를 가져 오기 위해 세션을 사용할 필요가 없습니다. 대신 "용도"를 사용해보십시오.

// $search already defined 

$query = User::where('active', '=', true); 

if(!empty($search->training)) { // one or many 
    $query = User::with(array('training' => function($query) uses ($search) { 
     // Now you can use $search in this context 
    })); 
} 

} 또한

, 당신이 당신의 관계를 소문자 문자열을 사용하고 있지만, 이렇게해야하므로 모델/클래스가 실제로 대문자 :

class User extends Eloquent { 

    public static $table = 'user'; 

    public function training(){ 
     return $this->has_many_and_belongs_to('Training', 'user_training'); 
    } 
} 

class Training extends Eloquent { 

    public static $table = 'training'; 

    public function users(){ 
     return $this->has_many_and_belongs_to('User', 'user_training'); 
    } 
} 

셋째, 선포 "$ query = User :: where ('active', '=', true);" 덮어 씁니다. 어쩌면 당신은 이것을 찾고 있습니다 :

if (!empty($search->training)) { // one or many 
    $query = User::with(array('training' => function($query) uses ($search) { 
     // Now you can use $search in this context 
     $query->where_in('training.id', $search->training); 
    })); 
} else { 
    $query = User::with(array()); 
} 
$query = $query->where('active', '=', true); 

나는 더 많은 통찰력을 줄 수 있지만 귀하의 최종 목표는 100 %가 아닙니다.

+0

감사합니다. uses 키워드에 대한 팁은 laravel 문서에서 본 적이 없다는 것을 의미합니다. – Matt

+0

최종 목표는 다중 선택에서 여러 "교육"항목을 선택할 수 있고 검색을 클릭하면 해당 교육 인증서가있는 사용자 만 반환합니다. – Matt

+0

job_title에서도 '사용'keyowrd를 사용할 수 있습니까? Deosnt가 작동하는 것 같습니다. 그 'subfunction'과 비슷한 상황. <- 언어 :! 랭 - PHP -> 경우 {// 하나 또는 여러 \t \t \t $ 질의 -> (함수 ($ 쿼리)를 사용 ((빈 ($ 검색 -> job_titles)!) $ 됨) { \t \t \t \t의 foreach ($ 검색 - $ ID로> job_titles) { \t \t \t \t \t $ 질의 -> or_where ('job_title_id' '='$ 아이디) \t \t \t \t } \t \t \t}); \t \t – Matt