2016-10-12 4 views
2

다른 테이블의 데이터를 가져 오는 선택적 조건을 기반으로 쿼리를 작성하고 싶습니다. 내 스키마는Laravel : 선택적 조건에 따라 variouos 테이블에서 데이터 가져 오기

myboxes 표와 같은

id, 
type_id --> foreign key to box_type table 
postal_code 
po_box 
created_at 
updated_at 

mybox_access 테이블

id 
mybox_id -> foreign key to myboxes table 
email 

id 
type_name 

그리고 여기 내 모델 MyBox.php 있습니다 box_type 테이블

를 찾습니다3210
class MyBox extends Model { 
    public function type() { 
     return this->hasOne(BoxType::class, 'id', 'type_id'); 
    } 

    public function access() id 
     return this->hasOne(MyBoxAccess::class, 'mybox_id', 'type_id'); 
    } 
} 

MyBoxType.php는 관계 선박 다음이

public function mybox() { 
     return this->hasOne(MyBox::class, 'id', 'type_id'); 
    } 

그리고 MyBoxAccess.php이

public function vbox() { 
     return $this->belongsTo(MyBox::class, 'id', 'mybox_id'); 
    } 

지금 내가 필요한 PARAM로 이메일을 조건 다음에 따라 취득 할 관계를 다음하고 postal_code 및 po_box를 선택적 매개 변수로 사용할 수 있습니다 (그러나 그 중 하나는 필수 매개 변수이고 둘 다있을 수도 있습니다).

그래서 나는 TYPE_ID 모든 my_boxes의 데이터를 얻으려면 또는 ID가 mybox_access 테이블 및 우편 _ 번호 또는 po_box에 이메일과 일치하는 모든 myboxes의 whoes이 PARAMS 우편의 단순 일치 myboxes 테이블

에 PARAMS에 일치하는 3 코드와 po_box 나는

$result = new MyBox(); 
if(!empty($request['postal_code'])) { 
    $result->where('postal_code', like, '%'.$request['postal_code']); 
} 
if(!empty($request['po_box'])) { 
    $result->where('po_box', like, '%'.$request['po_box']); 
} 
$result = $result->get(); 

같은 몇 가지 일을 쓸 수 있습니다하지만 위에서 언급 한 조건에 대한 데이터를 얻을하는 방법을 모르겠어요. 내가

MyBox::with(['access' => function(Builder $query) use ($request){ 
    $query->where('mybox_id',$request['id']); 
}])->get(); 

같은 with()을 사용하여이 작업을 수행 할 때 나는

`Argument 1 Passed to {closure}() must be an instance of Illuminat\Database\Query\Builder, instance of Illuminate\Databaase\Eloquent\Relation\HasOne given` 

어떤 몸이 제가이 쿼리 위에서 언급 한 조건

답변

1

$query은 빌더 인스턴스가 아닌 관계입니다.

이렇게하면 예외를 throw해서는 안됩니다.

MyBox::with(['access' => function ($query) { 
    $query->where('mybox_id', $request['id']); 
}])->get(); 

하지만 당신의 상자 < => 액세스 관계를 잘하지 않기 때문에 나는이 문제를 레졸 거라고 생각하지 않습니다. HasMany 여야합니다.

// MyBox.php 
public function type() 
{ 
    return $this->hasOne(BoxType::class, 'id', 'type_id'); 
} 
public function access() 
{ 
    return $this->hasMany(MyBoxAccess::class, 'mybox_id', 'id'); 
} 

컨트롤러에서 이렇게 할 수 있습니다.당신이 모든 조건을 병합 할 경우

// $results where type_id is 3 
$results = MyBox::where('type_id', 3)->get(); 

// List of boxes accessible by email 
$results = MyBox::whereHas('access', function ($query) { 
    $query->where('email', request()->input('email')); 
})->get(); 

// Results where postal_code and po_box matches the request 
$results = MyBox::with('access')->where(function ($query) { 
    if (request()->has('postal_code')) { 
     $query->where('postal_code', 'like', '%' . request()->input('postal_code')); 
    } 
    if (request()->has('po_box')) { 
     $query->where('po_box', 'like', '%' . request()->input('po_box')); 
    } 
})->get(); 

는 그리고 : 폐쇄에 사용하는 경우

$results = MyBox::where(function ($query) { 
    if (request()->has('type_id')) { 
     $query->where('type_id', request()->input('type_id')); 
    } 
    if (request()->has('email')) { 
     $query->whereHas('access', function ($query) { 
      $query->where('email', request()->input('email')); 
     }); 
    } 
    if (request()->has('postal_code')) { 
     $query->where('postal_code', 'like', '%' . request()->input('postal_code')); 
    } 
    if (request()->has('po_box')) { 
     $query->where('po_box', 'like', '%' . request()->input('po_box')); 
    } 
})->get(); 

내가 항상 request() 외관을 사용, 그것은 나에게 청소기 느낀다.

+0

'-> get()'을 세 번 사용합니까? –

+0

글쎄요. 3 가지 다른 종류의 결과를 요청했습니다 (type_id 또는 email 또는 postal_code/po_box를 기반로 함). 확실히'-> get()'만 사용할 수 있습니다. – SimonDepelchin

+0

@SimponDepelchin 잘 타입 ID와 emaill의 조건과 post_code 또는 po_box 중 하나가 있어야 할 때마다 하나의'-> get()'에서 그들을 어떻게 결합 할 수 있습니까? (type_id = 3 또는 email = myemail) 및 (post_code = 12 또는 po_box = 12)와 같은 위치는 어디입니까? –

0

에 따라 데이터를 얻을 수있는 방법을 알려 주시기 바랍니다 수 얻을 :

MyBox::with('access')->get(); 
+0

그리고 내가 quesiton에서 물어 온 모든 질문을 해결할 수 있을까요? –

관련 문제