2013-10-04 3 views
0

제품 테이블을 쿼리하고 관계가 존재하는 경우 컬렉션을 반환하려고합니다.Laravel 4 : 관계를 쿼리하여 관계가 존재하는 경우 행을 선택하십시오.

반복 한 아래 모든 제품 테이블의 행, 게으른로드 금속 테이블 $name 일치하는 경우를 쿼리합니다. 이것은 잘못된 것입니다.

내 노선 :

Route::group(array('prefix' => '{api}/v1'), function() 
{ 
    Route::controller('products', 'Api\V1\ProductController'); 
}); 

내 컨트롤러 :

public function getFilter($metal = null) { 
    $products = $this->product; 
    if ($metal) { 
     $products->with('metal', function($query, $metal) { 
      $query->where('name', $metal); 
     }); 
    } 
    return Response::api($products->get()); 
} 

가 난 단지$productsmetal.name = $metal 경우 표시 를 원한다. 예 : 의 답변을 기꺼이 도와의 일부를 사용하여

$this->products->where('metal.name', $metal)->get; 

솔루션 :

이가 조인하지 않고, 다른 방법 (2)를 제공합니다 같은.

http://paste.laravel.com/WC4

+0

는 * (http://laravel.com/docs/eloquent#eager-loading) * 열망로드 제약을 참조 [문서]에서보세요 . 배열을 * with * 함수에 대신 전달해보십시오 :'$ products-> with (array ('metal'=> function ($ query) use ($ metal) ...' –

답변

1

불행하게도 아직 설득력 하나 슬쩍으로이 작업을 수행 할 수 없습니다.

하지만,이 같은 역의 관계를 이용하여하는 방법이있다 : 이것은 당신을위한 우아한 해결책이없는 경우

public function getFilter($metal = null) 
{ 
    // filter the metals first 
    $metals = Metal::with('products')->where('name', '=' , $metal)->get(); 
    $products = array(); 
    foreach($metals as $metal) 
    { 
      // collect the products from the filtered metals 
      $products = array_merge($products, $metal->products->toArray()); 
    } 
    return $products; 
} 

, 쿼리를 구성 유창함을 사용하고 제품에 가입해야합니다 중 하나는 x 금속 테이블을 수동으로 가져 오거나 newQuery() 메서드를 재정 의하여이를 사전에 조인 할 수 있습니다.

1) 대체 접근법 1.

public function getFilter($metal = null) { 
    return DB::table('products')->join('metal', 'products.id', '=' , 'metal.product_id') 
         ->where('metal.name', $name) 
         ->select(array('products.*')); 
} 

2) 다른 접근은 두

class Product extends Eloquent{ 

public function newQuery($excludeDeleted = true){ 
     return parent::newQuery()->join('metal','id','=','metal.product_id'); 
    } 

} 
관련 문제