반응형
Laravel에서 이것을 수행하는 방법, 하위 쿼리
Laravel에서이 쿼리를 어떻게 만들 수 있습니까?
SELECT
`p`.`id`,
`p`.`name`,
`p`.`img`,
`p`.`safe_name`,
`p`.`sku`,
`p`.`productstatusid`
FROM `products` p
WHERE `p`.`id` IN (
SELECT
`product_id`
FROM `product_category`
WHERE `category_id` IN ('223', '15')
)
AND `p`.`active`=1
조인으로도이 작업을 수행 할 수 있지만 성능을 위해이 형식이 필요합니다.
이 코드를 고려하십시오.
Products::whereIn('id', function($query){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', ['223', '15'])
->where('active', 1);
})->get();
Fluent에 대한 고급 wheres 문서를 살펴보십시오 : http://laravel.com/docs/queries#advanced-wheres
다음은 달성하려는 작업의 예입니다.
DB::table('users')
->whereIn('id', function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
그러면 다음이 생성됩니다.
select * from users where id in (
select 1 from orders where orders.user_id = users.id
)
키워드 "use ($ category_id)"를 사용하여 변수를 사용할 수 있습니다.
$category_id = array('223','15');
Products::whereIn('id', function($query) use ($category_id){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', $category_id )
->where('active', 1);
})->get();
다음 코드가 저에게 효과적이었습니다.
$result=DB::table('tablename')
->whereIn('columnName',function ($query) {
$query->select('columnName2')->from('tableName2')
->Where('columnCondition','=','valueRequired');
})
->get();
Eloquent는 다양한 쿼리에서 사용할 수 있으며 이해하고 관리하기 쉽게 만들 수 있습니다.
$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
->select('product_id'); //don't need ->get() or ->first()
그리고 우리는 모두 합쳤습니다.
Products::whereIn('id', $productCategory)
->where('active', 1)
->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
->get();//runs all queries at once
이렇게하면 질문에 작성한 것과 동일한 쿼리가 생성됩니다.
Laravel 4.2 이상에서는 try 관계 쿼리를 사용할 수 있습니다.
Products::whereHas('product_category', function($query) {
$query->whereIn('category_id', ['223', '15']);
});
public function product_category() {
return $this->hasMany('product_category', 'product_id');
}
Product::from('products as p')
->join('product_category as pc','p.id','=','pc.product_id')
->select('p.*')
->where('p.active',1)
->whereIn('pc.category_id', ['223', '15'])
->get();
변수 사용
$array_IN=Dev_Table::where('id',1)->select('tabl2_id')->get();
$sel_table2=Dev_Table2::WhereIn('id',$array_IN)->get();
참고 URL : https://stackoverflow.com/questions/16815551/how-to-do-this-in-laravel-subquery-where-in
반응형
'program story' 카테고리의 다른 글
JSON 문자열에서 C # 클래스 파일을 자동 생성하는 방법 (0) | 2020.08.20 |
---|---|
presentModalViewController : Animated는 ios6에서 더 이상 사용되지 않습니다. (0) | 2020.08.20 |
정의에 변수를 포함하는 GNU make의 목표 / 타겟 나열 (0) | 2020.08.20 |
영업일 계산 (0) | 2020.08.20 |
pycharm은 탭을 공백으로 자동으로 변환합니다. (0) | 2020.08.20 |