반응형
Larabel에서 이 작업을 수행하는 방법, 서브쿼리:
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의 고급 where 절 문서를 참조하십시오.다음은 고객이 달성하고자 하는 작업의 예입니다.
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();
다양한 쿼리에서 웅변을 사용하여 보다 쉽게 이해하고 유지할 수 있습니다.
$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 8.x에 대한 접근법은 다음과 같습니다.여러 답변에서 수집한 것입니다.
- 쿼리 작성기를 사용하고 SQL을 직접 작성하지 마십시오.
- 모델을 사용하여 모든 것을 결정하십시오.하드코드된 테이블 이름이나 이름(열 등)을 사용하지 마십시오.
Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
->whereIn('id', ProductCategory::select(['product_id'])
->whereIn('category_id', ['223', '15'])
)
->where('active', 1)
->get();
이 스크립트는 Larabel 5.x 및 6.x에서 테스트됩니다.그static
닫힘으로 인해 성능이 향상될 수 있습니다.
Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
->whereIn('id', static function ($query) {
$query->select(['product_id'])
->from((new ProductCategory)->getTable())
->whereIn('category_id', [15, 223]);
})
->where('active', 1)
->get();
SQL을 생성합니다.
SELECT `id`, `name`, `img`, `safe_name`, `sku`, `productstatusid` FROM `products`
WHERE `id` IN (SELECT `product_id` FROM `product_category` WHERE
`category_id` IN (?, ?)) AND `active` = ?
다음의 코드가 유효했습니다.
$result=DB::table('tablename')
->whereIn('columnName',function ($query) {
$query->select('columnName2')->from('tableName2')
->Where('columnCondition','=','valueRequired');
})
->get();
Larabel 4.2 이상에서는 try relationship 쿼리를 사용할 수 있습니다.
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();
사용하다DB::row
서브쿼리를 설정합니다.
예
DB::raw('(SELECT
`product_id`
FROM `product_category`
WHERE `category_id` IN ('223', '15')) as product_id ')
변수 사용
$array_IN=Dev_Table::where('id',1)->select('tabl2_id')->get();
$sel_table2=Dev_Table2::WhereIn('id',$array_IN)->get();
이 온라인 도구 sql2builder를 사용해 보십시오.
DB::table('products')
->whereIn('products.id',function($query) {
DB::table('product_category')
->whereIn('category_id',['223','15'])
->select('product_id');
})
->where('products.active',1)
->select('products.id','products.name','products.img','products.safe_name','products.sku','products.productstatusid')
->get();
언급URL : https://stackoverflow.com/questions/16815551/how-to-do-this-in-laravel-subquery-where-in
반응형
'source' 카테고리의 다른 글
키가 mariadb로 너무 깁니다만, 같은 인코딩의 스크립트가 mysql로 동작합니다. (0) | 2022.10.15 |
---|---|
mysql 워크벤치 EER 열기 오류 (0) | 2022.10.15 |
Javascript - 내부가 없는 컨테이너 요소에 HTML 추가HTML (0) | 2022.10.15 |
데바운스 어떻게 해요? (0) | 2022.10.15 |
Java SE와 Java EE의 주요 차이점은 무엇입니까? (0) | 2022.10.15 |