How can I use 'AS' in my count query? - mysql

How can I use AS in my count query?
Actually i want to result like { "count":"number" } for json result. I dont know what should i call this thing?
public function firstHourTrades(){
$user_id = Auth::user()->id;
$data = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->where('finaltrade.user_id', $user_id)
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
->count();
return response()->json($data);
}

You could also do a raw select and manually assign the alias:
$data = DB::table('finaltrade')
->select(DB::raw('count(*) as count'))
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->where('finaltrade.user_id', $user_id)
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '>=', DB::raw('exchanges.start_time'))
->whereTime(DB::raw('IF(finaltrade.buy_datetime<finaltrade.sell_datetime, finaltrade.buy_datetime, finaltrade.sell_datetime) '), '<=', DB::raw("ADDTIME(exchanges.start_time, '1:00:00')"))
->get();

Related

Adding OR statements to Eloquent Queries

I need a little help regarding the syntax of Eloquent. I want to add more where clauses but can't get the OR working. I read https://laravel.com/docs/7.x/queries#where-clauses but my statement fails.
Works:
$events = DB::table('events')->select('id','resourceId','title','start','end')
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)->get();
Does not work:
$events = DB::table('events')->select('id','resourceId','title','start','end')
->whereDate('start', '>=', $start)->whereDate('end', '<=', $end)
->orWhere(function($query) {
$query->whereDate('start', '<=', $start)
->whereDate('end', '>=', $end);
})
->get();
Is orWhere not supposed to work with whereDate?
First; while using closures you need to pass arguments with use. You may or two main conditions and in their nested conditions both sub-conditions will be anded.
public function index()
{
DB::table('events')
->select('id', 'resourceId', 'title', 'start', 'end')
->where(function ($query) use ($start, $end) {
$query->whereDate('start', '>=', $start)->whereDate('end', '<=', $end);
})
->orWhere(function ($query) use ($start, $end) {
$query->whereDate('start', '<=', $start)->whereDate('end', '>=', $end);
})
->get();
}
This function will print (don't mind about the dates, just example)
SELECT `id`, `resourceId`, `title`, `start`, `end`
FROM `events`
WHERE (date(`start`) >= '2020-06-15' and date(`end`) <= '2020-06-16')
or (date(`start`) <= '2020-06-15' and date(`end`) >= '2020-06-16')

Laravel where and orWhere function

I'm trying to count how many tickets our operators have closed in a week(and per day) I have these 2 queries
$closedWeek = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
->where([
['activity_log.created_at', '>', $fri],
['activity_log.user_id', '=', $id],
['activity_log.event_name', '=', 'ticket_closed'],
['number', 'like', 'SD%']
])->count();
$closedWeek2 = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
->where([
['activity_log.created_at', '>', $fri],
['activity_log.user_id', '=', $id],
['number', 'like', 'SD%'],
['activity_log.event_name', '=', 'ticket_department_updated']
])
->where(function($query) {
$query->where('activity_log.new_value', '=', 'closed Uninvoiced')
->orWhere('activity_log.new_value', '=', 'To Invoice')
->orWhere('activity_log.new_value', '=', 'closed Other')
->orWhere('activity_log.new_value', '=', 'closed Invoiced');
})->count();
$closedWeek = $closedWeek + $closedWeek2;
They are bringing back slightly bigger numbers than expected and I think some of them are duplicated. How could I put these into one query using where(function($query)) or do I have to use DB::raw instead? I can then count unique ids
You can use GroupBy(); with id,
Example:
$closedWeek = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
->where([
['activity_log.created_at', '>', $fri],
['activity_log.user_id', '=', $id],
['activity_log.event_name', '=', 'ticket_closed'],
['number', 'like', 'SD%']
])
->groupBy('ticket.id')
->count();
$closedWeek2 = Ticket::join('activity_log', 'activity_log.rel_id', '=', 'ticket.id')
->where([
['activity_log.created_at', '>', $fri],
['activity_log.user_id', '=', $id],
['number', 'like', 'SD%'],
['activity_log.event_name', '=', 'ticket_department_updated']
])
->whereIn('activity_log.new_value',
[ 'closed Uninvoiced',
'To Invoice',
'closed Other',
'closed Invoiced',
])
->groupBy('ticket.id')
->count();
$closedWeek = $closedWeek + $closedWeek2;
OBS:
You dont need '=', on equal wheres, example, where('colun', '=', 'abc'); you can change to where('colun', 'abc');
Please test and see if you have the expected result.
References:
How to get distinct values for non-key column fields in Laravel?

Laravel Eloquent query for join with like

I have this raw query but I'm struggling to convert it to eloquent. Below is my raw sql. I cannot use DB:select because i'm using paginate at the end.
select * from orders
join users on orders.user_id = users.id
where orders.id = $search
or orders.reference_no like '%$search%'
or users.name like '%$search%'
public function customer()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
$orders = Order::where('reference_no', 'LIKE', "%$search%")
->orWhere('reference_no',$search)
->orWhere('id',$search)
->whereHas('customer', function ($query) use ($search) {
$query->where('name', 'like', '%$search%');
})
->paginate(10);
Try this
$result = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'user.users.id')
->where(function($q) {
$q->where('orders.id', $search)
->orWhere('orders.reference_no', 'like', "%$search%")
->orWhere('users.name', 'like', "%$search%") ;
})
->get();
Thanks Pavel and Unai. Based on your answer manage to do this. Need to do a 'use' and in te orWhere I need to concat '%' to the actual $search variable. If I dont have concat '.' literal search is shown in the query
$orders = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'users.id')
->where(function($q) use ($search) {
$q->where('orders.id', $search)
->orWhere('orders.reference_no', 'like', '%' . $search . '%')
->orWhere('users.name', 'like', '%' . $search .'%') ;
})
->paginate(10);
Try this
$result = Order::select('orders.*')
->join('users', 'orders.user_id', '=', 'user.users.id')
->where(function($q) use ($search){
$q->where('orders.id', $search)
->orWhere('orders.reference_no','like', '%$search%')
->orWhere('users.name','like', '%$search%') ;
})
->get();

CURDATE() with laravel 5

I'm new to laravel and i am wanting to use multiple where clauses and use curdate().
This is an example :
$data = DB::table('toutcome')->where('date', '>=', curdate())->where('Status', '=', 'A')->count('AppID');
return view('home', compact('data'));
It's not working at all.
So along with the answers in the comments:
public function index()
{
// First query with DB::raw() variant
$data = DB::table('toutcome')
->where('date', '>=', DB::raw('curdate()'))
->where('Status', '=', 'A')
->count('AppID');
// Second query with Carbon variant
$data2 = DB::table('toutcome')
->where('date', '>=', Carbon::now())
->where('Status', '=', 'A')
->count('AppID');
// Third query with '#Sunny' whereRaw variant
$data3 = DB::table('toutcome')
->whereRaw('date >= curdate()')
->where('Status', '=', 'A')
->count('AppID');
return view('home', compact('data','data2','data3'));
}
I'm not a big fan of compact() personally so I would write:
return view('home', ['data'=>&$data,'data2'=>&$data2,'data3'=>&$data3])
although personally (if you want to read on taking it further) read up on ViewComposers:
https://laravel.com/docs/master/views#view-composers
Change
where('date', '>=', curdate())
to
whereRaw('date >= curdate()')

Laravel query builder advanced wheres AND, OR

$query = new TableA;
$query = $query->join('tableB', 'tableA.b_id', '=', 'tableB.id');
$query = $query->where('tableB.something', '=', '1');
$query = $query->where('tableA.something_else', '=', '2');
And it produces:
WHERE something=1 AND something_else=2 AND .. AND....
BUT now - I need this:
WHERE something=1 AND something_else=2 AND (city=city1 OR city=city2 OR city=city3) AND (country=country1 OR country=country2)
Any ideas?
Make use of Advanced Wheres. For your example, it'd be something like this:
->where(function ($query) {
$query->where('city', '=', city1)
->orWhere('city', '=', city2)
->orWhere('city', '=', city3);
})->where(function ($query) {
$query->where('country', '=', country1)
->orWhere('country', '=', country2);
});
Quick method. Read about raw expressions:
http://laravel.com/docs/queries#raw-expressions