简体   繁体   中英

Laravel 4 Query Builder SQL Statement

Good day, I have this SQL statement and I'm having a difficulty on how to convert this in Laravel Query.

I read the docs in http://laravel.com/docs/4.2/queries and I'm confused. Any help would do.

SELECT count(*) FROM `transactions` WHERE `borrower_id` = 2 
            AND `book_id` = 2 AND (
                (
                    `reservedDate` IS NOT NULL 
                    and `borrowedDate` IS NULL
                ) 
                OR (
                    `borrowedDate` IS NOT NULL 
                    AND `returnedDate` IS NULL
                )
            )

So I try to build this query by reading the documentations from Laravel. Still haven't tested it yet but hope it could give you the right direction.

Maybe next time, you should show your own query (it's ok if it's not correct). It's easier to get start from there.

$super_query = DB::table('transactions')->where('borrower_id' , '=' , 2)->where('book_id', '=' , 2)->where( function ( $query ) {
$query->where(function ($query1) {
    $query1->whereNotNull('reservedDate')->whereNull('borrowedDate')
)->orWhere(function ($query2) {
    $query2->whereNotNUll('borrowedDate')->whereNull('returnedDate')
})  
})->count();
    DB::table('transactions')
  ->Where('borrower_id', '=', 2)
  ->Where('book_id', '=', 2)
  ->where(function($query)
  {
    $query->where(function($query1) {
      $query1->whereNotNull('reservedDate')
             ->whereNull('borrowedDate');

    })
    ->orWhere(function($query2) {
      $query2->whereNotNull('borrowedDate')
             ->whereNull('returnedDate');
  });
})->count();

try this.. this will result into

select count(*) from `transactions` where `borrower_id` = 2 and `book_id` = 2 and ((`reservedDate` is not null and `borrowedDate` is null) or (`borrowedDate` is not null and `returnedDate` is null))

Try this:

Eloquent

Transactions::where('borrower_id', '=', 2)
    ->where('book_id', '=', 2)
    ->where(function($query)
    {
        $query->whereNotNull('reservedDate')
                ->whereNull('borrowedDate');
    })
    ->orWhere(function($query)
    {
        $query->whereNotNull('borrowedDate')
                ->whereNull('returnedDate');
    })
    ->count();
book::count()->where('borrower_id','=','2','book_id','=',2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM