Raw Expression in Laravel? - sql

My sql code is :
Select * from table where cond(condition)1 and con2 ...... and(conX or conY).
How can i write it with raw expression. I don't know the keywork to solve this.
Update: My code is :
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... ;
if(something != true) $builder->whereRaw(conX);
else $builder->whereRaw((conX or ConY));
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... and (conX or conY);
OK, it work, but i need to write conX 2 times, though it too long. So now i want to contract it.
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... and conX;
if(something = true) $builder->raw or do something; (#)
//$builder->to sql = Select * from table where cond(condition)1 and con2 ...... and (conX or conY);
The question is that: What i should do in the (#) line to make the result as i expected

Try:
if (something == true) {
$result = DB::table('table')
->selectRaw('*')
->where(condition1)
->where(condition2)
->get();
}
Or:
if (something == true) {
$result = DB::table('table')
->select(DB::raw(YOUR SQL STATEMENT))
->get();
}
Further read:
https://laravel.com/docs/5.5/queries

Related

Laravel Query: implement Eloquent Scope for Query Builder

In the Laravel Query Builder I want to implement something like Scope in Eloquent.
Ref: Laravel Queries: Adding custom feature like Soft Deletes.
I have some complex queries (with joins and what not) but I want to be able to easily apply a WHERE condition that works as follows:
original:
Select * from t1 join t2 ... join t3 ... etc
Where t1.c1 = x OR t3.c4 like "%like"
wanted:
Select * from t1 join t2 ... join t3 ... etc
Where (t1.c1 = x OR t3.c4 like "%like") AND (t1.isTest = false AND t3.isTest = false)
I have written the following method:
public static function scopeNoTest($query, $tables=[false])
{
if (!is_array($tables)) $tables = [$tables];
foreach ($tables as $table)
{
$field = ($table) ? $table . '.isTest' : 'isTest';
$query = $query->where(function ($q) use ($query, $field)
{
$q->where($field, false)
->orWhereNull($field);
}
);
}
return $query;
}
It gets run like this:
$select = <parameter driven select statement>
$where[$role] = <array of different where condition based on passed in parameter?
$bindings = <query bindings based on passed in parameters>
$query = DB::table('Transactions AS trans')
->leftJoin('Buyers AS b', 'trans.ID', '=', 'b.Transactions_ID')
->leftJoin('Sellers AS s', 'trans.ID', '=', 's.Transactions_ID')
->leftJoin('Agents AS ba', 'trans.BuyersAgent_ID', '=', 'ba.ID')
->leftJoin('Agents AS sa', 'trans.SellersAgent_ID', '=', 'sa.ID')
->leftJoin('TransactionCoordinators AS btc', 'trans.BuyersTransactionCoordinators_ID', '=', 'btc.ID')
->leftJoin('TransactionCoordinators AS stc', 'trans.SellersTransactionCoordinators_ID', '=', 'stc.ID')
->leftJoin('lu_UserRoles AS lu_ur', 'trans.ClientRole', '=', 'lu_ur.Value')
->leftJoin('Properties AS p', 'trans.Properties_ID', '=', 'p.ID')
->selectRaw($select);
// ... Adds code to Only Select records with isTest NOT True
$query = Model_Parent::scopeNoTest($query, ['trans', 'ba', 'sa', ]);
$query->whereRaw($where[$role].$whereUser, $bindings)->distinct();
$transactions = $query->get();
The problem with this code is that it does not put the original [passed in] query in parentheses - so the query is wrong!.
The WHERE the code creates is:
where
(`trans`.`isTest` = 0 or `trans`.`isTest` is null)
and (`ba`.`isTest` = 0 or `ba`.`isTest` is null)
and (`sa`.`isTest` = 0 or `sa`.`isTest` is null)
and trans.BuyersTransactionCoordinators_ID = 1 OR trans.SellersTransactionCoordinators_ID = 1
OR trans.CreatedByUsers_ID = 1 OR trans.OwnedByUsers_ID = 1
And I want
where
(`trans`.`isTest` = 0 or `trans`.`isTest` is null)
and (`ba`.`isTest` = 0 or `ba`.`isTest` is null)
and (`sa`.`isTest` = 0 or `sa`.`isTest` is null)
and (trans.BuyersTransactionCoordinators_ID = 1 OR trans.SellersTransactionCoordinators_ID = 1
OR trans.CreatedByUsers_ID = 1 OR trans.OwnedByUsers_ID = 1)
Is there a way to do this ??
It looks like the following line is causing this:
$query->whereRaw($where[$role].$whereUser, $bindings)->distinct();
I think there are two ways to solve this:
// 1
->whereRaw('(' . $where[$role].$whereUser . ')', $bindings)->
// 2
->where(function ($query) use (...) {
$query->whereRaw(...);
})->

how can i nest two AND queries in Doctrine2 using createQueryBuilder?

following is my query :
$em = \Zend_Registry::get('em');
$qb_1 = $em->createQueryBuilder();
$q_1 = $qb_1->select('link_req')
->from('\Entities\link_requests','link_req')
->where( 'link_req.is_confirmed = 1' )
->andWhere('link_req.$link_requestsSenderUser='.$user1_id .'or'.' link_req.$link_requestsSenderUser='.$user2_id)
->andWhere('link_req.$link_requestsReceiverUser='.$user1_id .'or'.' link_req.$link_requestsReceiverUser='.$user2_id);
$result= $q_1->getDql();
echo $result;
and i want following query:
SELECT * FROM [fb_local].[dbo].[link_requests]
WHERE is_confirmed = 1 AND (request_user_id = 12 or request_user_id=19) AND (accept_user_id = 12 or accept_user_id = 19)
Your SQL is just 1 query, so not sure what you're trying to nest. But try the following:
$em = \Zend_Registry::get('em');
$qb_1 = $em->createQueryBuilder();
$q_1 = $qb_1->select('link_req')
->from('\Entities\link_requests','link_req')
->where( 'link_req.is_confirmed = 1' )
->andWhere('link_req.link_requestsSenderUser=:user_id or link_req.link_requestsSenderUser=:user_id')
->andWhere('link_req.link_requestsReceiverUser=:user_id or link_req.link_requestsReceiverUser=:user_id');
$q_1->setParameter('user_id', $user1_id);
$query = $q_1->getQuery();
echo $query->getSql();
Notice how I removed the $ in front of link_requestsReceiverUser. I also made a parameter from $user1_id, this prevents SQL injections.

Dynamic where in a Sql Select Query

i would like to create a sql query like these :
Select* from Table where
(if picod=1)
{
dvdt= "xxxx"
}
(if picod=2)
{
cddt= "xxxx"
}
(if picod=3)
{
bldt= "xxxx"
}
(if picod=3)
{
fadt= "xxxx"
}
I don't know how doing this in SQL .
Anyone could help me please ?
Thanks a lot :)
Select* from Table
where (picod=1 and dvdt= 'xxxx') or (picod=2 and cddt= 'xxxx') or ....... (XXXX) or....
Just use OR
SELECT *
FROM Table
WHERE (Picod = 1 AND dvdt = 'xxxx')
OR (Picod = 2 AND cddt = 'xxxx')
OR (Picod = 3 AND bldt = 'xxxx')
OR (Picod = 3 AND fadt = 'xxxx');
SELECT *
FROM Table
WHERE 'xxxx' = case Picod
when 1 then dvdt
when 2 then cddt
when 3 then bldt
when 4 then fadt
end

How to convert this SQL to LINQ or Lambda expression?

here's my sql query below:
Can you guys help me to convert this to a much cleaner one??
SELECT [PurchaseRequestID], [ProjectID],[FullName]
FROM PurchaseRequest
WHERE [PurchaseRequestID] IN
(SELECT [PurchaseRequestID] FROM PurchaseRequestDetail )
AND [PurchaseRequestID] NOT IN
(SELECT [PurchaseRequestID] FROM [PurchaseOrder] )
Though i have already converted this successfuly, i think this is not readable and needs to be rewritten:
var query = from a in db.PurchaseRequests
where
(from b in db.PurchaseRequestDetails
select new
{
b.PurchaseRequestID
}).Contains(new { a.PurchaseRequestID }) &&
!(from c in db.PurchaseOrders
select new
{
c.PurchaseRequestID
}).Contains(new { a.PurchaseRequestID })
select a;
thanks
you really don't need all those anonymous objects. Use the let keyword to introduce temporary variables instead of doing operations on the subqueries directly.
from a in db.PurchaseRequests
let b = from b in db.PurchaseRequestDetails select b.PurchaseRequestID
let c = from c in db.PurchaseOrders select c.PurchaseRequestID
where b.Contains(a.PurchaseRequestID) && !c.contains(a.PurchaseRequestID)
select a;
var query = from a in db.PurchaseRequests
where
db.PurchaseRequestDetails.Any(x => x.PurchaseRequestID == a.PurchaseRequestID) &&
!db.PurchaseOrders.Any(x => x.PurchaseRequestID == a.PurchaseRequestID)
select a;
If you have navigation properties set up, you can write the query like this:
IQueryable<PurchaseRequest> query =
from purchaseRequest in myDataContext.PurchaseRequests
where purchaseRequest.PurchaseRequestDetail.Any()
where !purchaseRequest.PurchaseOrder.Any()
select purchaseRequest;
Or this lambda/method style if you prefer...
IQueryable<PurchaseRequest> query2 = myDataContext.PurchaseRequests
.Where(purchaseRequest => purchaseRequest.PurchaseRequestDetail.Any())
.Where(purchaseRequest => !purchaseRequest.PurchaseOrder.Any());

Linq to SQL Case WHEN in VB.NET?

How do I do a Case WHEN in Linq to SQL (vb.net please).
In SQL it would be like this:
SELECT
CASE
WHEN condition THEN trueresult
[...n]
[ELSE elseresult]
END
How would I do this in Linq to SQL?
var data = from d in db.tb select new {
CaseResult = If (d.Col1 = “Case1”, "Case 1 Rised", If (d.Col1 = “Case2”, "Case 2 Rised", "Unknown Case"))
};
Check This Out
var data = from d in db.tb select new {
CaseResult = (
d.Col1 == “Case1” ? "Case 1 Rised" :
d.Col1 == “Case2” ? "Case 2 Rised" :
"Unknown Case")
};
Please Note that [ ? Symbol = then] , [ : Symbol = Or].
I haven't tried this but you may be able to do something like:
Dim query = From tbl In db.Table _
Select result =_
If(tbl.Col1 < tbl.Col2,"Less than",_
If(tbl.Col1 = tbl.Col2,"Equal to","Greater than"))
You would just need to keep nesting the If functions to handle all of your cases.
You can find more examples of various queries at http://msdn.microsoft.com/en-us/library/bb386913.aspx