2017-11-15 1 views
7

누구든지 아래의 SQL 문의 DB 쿼리 버전을 작성하는 데 도움을주십시오. select 문과 분할 된 조인에 대해 약간의 도움이 필요합니다.원시 쿼리에서 laravel 쿼리

나는 이것을 지금까지 해왔다.

$query = DB::table(raw('SapakInAdminOrder a')) 
->select(raw('a.*')) 
->leftJoin(raw('currency cu'), 'a.currency', '=', 'cu.id') 
->leftJoin(raw('moodboards m'), 'a.orderMoodboardID', '=', 'm.id') 
->join(raw('clients b'), 'a.clientID', '=', 'b.id') 
->leftJoin(raw('moodboards mc'), 'b.moodboardID', 'mc.id') 
->join(raw('sapakim c'), 'b.sapakID', '=', 'c.id') 
->leftJoin(raw('sapakim sm'), 'c.managerid', '=', 'sm.id') 
->leftJoin(raw('products p'), 'a.productKey', '=', 'p.id') 
->where(function ($query) { 
    $query->whereNull('a.isDeleted'); 
    $query->orWhere('a.isDeleted', '!=', 1); 
}); 

그러나 이것을 달성해야합니다.

select * from (select ROW_NUMBER() OVER(ORDER BY case when (indesign.status=4 or indesign.statusdate is null) then getdate()+2 else indesign.statusdate end ASC) AS RowNum,a.* 
FROM sapakInAdminOrder a 
left join currency cu on cu.id=a.currency 
left join moodboards m on m.id=a.orderMoodboardID 
inner join Clients b on a.clientID=b.id 
left join moodboards mc on mc.id=b.moodboardID 
inner join Sapakim c on b.sapakID=c.id 
left join Sapakim sm on sm.id=c.managerid 
left join products p on p.id=a.productKey 
left join (select * from (select ROW_NUMBER() over(PARTITION BY orderID ORDER BY id DESC) r, * from orderCommunication) f where r=1) chat on chat.orderId = a.id 
left join (select id,[status],orderid,approveSMSDate,coverImage,statusDate from (SELECT id,[status],statusDate,approveSMSDate,coverImage,orderid,ROW_NUMBER() OVER(PARTITION BY orderid ORDER BY id DESC) AS r FROM SapakimInAdminDesigns) f where r=1) indesign on a.id=indesign.orderid 
where (a.isDeleted is null or a.isDeleted != 1) and 
     c.inAdminManagerID=(select id from sapakim where sapakguid='test') and 
     c.sapakguid='test' and 
     a.isFreeDesign=0 and 
     a.transactionID = -1 and 
     (a.designerPaid is null or a.designerPaid=0) and 
     (chat.sentToPrinter is null and chat.sentToManager is null and chat.sentToDesigner is null) 
) bb where RowNum>=1 and RowNum<31 
ORDER BY RowNum asc 

나는 간단한 것들을 할 수 있지만, 아주 정말 조인 구획 된 및 선택 문 주위에 내 머리를 정리하지 못했습니다.

정말 감사드립니다.

미리 감사드립니다.

+0

예상되는 결과와 함께 테스트 스키마를 설정하고 일부 데이터를 시드하기 위해 일부 SQL을 공유하는 것이 도움이됩니다. –

답변

0

나는 또한 이런 유형의 문제에 얽매여 있지만 솔루션과 나에게 잘 작동한다.

사용 DB :: 준비가() 이러한 유형의 쿼리에 대한 :

$path = base_path() . "/storage/agency.sql"; 
$sql = file_get_contents($path); 
DB::unprepared(DB::raw($sql)); 

모든 SQL 명령 Laravel에서 기본적으로 준비가되어 있습니다,하지만 때로는 당신이 준비되지 않은 모드에서 명령을 실행해야 일부 데이터베이스의 일부 명령은 준비 모드에서 실행될 수 없기 때문입니다.

+0

간단히 DB :: query()를 사용하여 쿼리 할 수 ​​있지만 이는 훌륭한 해결책이 아닙니다. –

+0

DB :: unprepared는 원시 쿼리를 실행하며 DB :: raw는 필요하지 않습니다. 텍스트 파일 (특히 저장소 폴더에있는 파일)에서 쿼리를로드하면 파일이 유출 될 경우 문제를 묻습니다.저장소 패턴을 사용하고 소스 코드에서 DB :: select()를 사용하는 것이 훨씬 좋습니다. –

0

이게 무슨 뜻인가요?

$result = DB::Select("select * from (select ROW_NUMBER() OVER(ORDER BY case when (indesign.status=4 or indesign.statusdate is null) then getdate()+2 else indesign.statusdate end ASC) AS RowNum,a.* 
FROM sapakInAdminOrder a 
left join currency cu on cu.id=a.currency 
left join moodboards m on m.id=a.orderMoodboardID 
inner join Clients b on a.clientID=b.id 
left join moodboards mc on mc.id=b.moodboardID 
inner join Sapakim c on b.sapakID=c.id 
left join Sapakim sm on sm.id=c.managerid 
left join products p on p.id=a.productKey 
left join (select * from (select ROW_NUMBER() over(PARTITION BY orderID ORDER BY id DESC) r, * from orderCommunication) f where r=1) chat on chat.orderId = a.id 
left join (select id,[status],orderid,approveSMSDate,coverImage,statusDate from (SELECT id,[status],statusDate,approveSMSDate,coverImage,orderid,ROW_NUMBER() OVER(PARTITION BY orderid ORDER BY id DESC) AS r FROM SapakimInAdminDesigns) f where r=1) indesign on a.id=indesign.orderid 
where (a.isDeleted is null or a.isDeleted != 1) and 
     c.inAdminManagerID=(select id from sapakim where sapakguid='test') and 
     c.sapakguid='test' and 
     a.isFreeDesign=0 and 
     a.transactionID = -1 and 
     (a.designerPaid is null or a.designerPaid=0) and 
     (chat.sentToPrinter is null and chat.sentToManager is null and chat.sentToDesigner is null) 
) bb where RowNum>=1 and RowNum<31 
ORDER BY RowNum asc"); 
+0

그것은 DB :: query()가 될 것이지만, 여전히 내가 의미하는 바가 아니기 때문에 –

0

아마도 이러한 분할 된 쿼리에 대한 데이터베이스 뷰를 만들어야합니까? 그런 다음 나중에 데이터베이스에서보기에 참여할 수 있습니다.

기술적으로 이러한 분석 함수는 일반적으로 프레임 워크에서 지원되지 않습니다.

+0

이것은 laravel에서 이것을 할 수있는 방법이 없음을 의미합니까? –

+0

모든 DB-S가 분석 기능을 지원하는 것은 아닙니다. ORM-s는 보편적이며 모든 가능한 DB 엔진을 지원하도록 만들어졌습니다. ORM에서 이러한 정교한 쿼리를 구현할 필요가 없으며 대부분의 사람들은 존재를 알지조차 모릅니다. JOOQ와 같은 일부 예외가 있지만 PHP 언어는 아닙니다 (https://blog.jooq.org/2013/11/03/probably-the-coolest-sql-feature-window-functions/). – Aret

0

오라토리 (Orator)라는 새로운 Laravel 도구를 확인하십시오. 단순히 "기존"SQL을 붙여 넣을 수 있으며 Laravel의 DB Query Builder 구문을 반환합니다. 당신은 프론트 엔드에 표시 관계가 웅변 모델을 재치 사용하고자하는 가정

Laravel Orator News Article

Online Conversion Tool

0

, 모델 사용자에 https://laravel.com/docs/master/eloquent-relationships#one-to-one

식별라는 한 것과 관련이있다 당신이 $ user 변수를 전달한 것으로 가정하는 쇼 뷰로 이동하면, phone() 메소드에 의해 다음을 수행하십시오 :

<?php dd($user->phone); ?> 

당신이 이것을 의미하지 않는다면 질문의 요점을 놓칠 수도 있습니다.