I'm trying to rewrite MYSQL query using Laravel query builder
So this is the query
DB::select("SELECT * FROM accomodation WHERE id NOT IN
(SELECT accomodation_id FROM bookings
WHERE (`checkin` <= '$request->in' AND `checkout` >= '$request->out'));");
And this is what I've done so far
Accommodation::whereNotIN('id', function($q)
{
$q->select('accomodation_id')
->from('bookings')
->where('checkin', '<=', '$request->out')
->where ('checkout', '>=', '$request->in');
})
->get();
The problem is the first query is giving me expected results but the second one isn't
Can someone point out what I'm doing wrong?
I think you type it wrong. Look at the $request->in and $request->out. You may want to flip it. and why you use '$request->in' instead of $request->in. It will parse as string instead of the value
You don't have use. For example php Accommodation::whereNotIN('id', function($q) use ($request) and you need to flip condition with request ;)
Related
I want to show "cars.name" in result.
I need to use "cars.name" value to order later
$this->model
->select("pieces.*", "cars.name")
->where('cars_id', $carId)
->with('cars')
->has('cars', '>=', 1);
How can I do that?
You can try to do it this way by passing a closure function in with():
$this->model
->select("pieces.*")
->where('cars_id', $carId)
->with('cars'=> function ($query) {
$query->select('id','name');
}])
->has('cars', '>=', 1);
It will only select id and username from other table.
Remember that the primary key (id in this case) needs to be the first param in the $query->select() to actually retrieve the necessary results.
the first you have built is just a query, then it needs to be retrieved on the server, use get() and you will see error message. Need more info about the relation between pieces and cars to help. Try it -
$this->model::whereHas('cars',function(builder $query)use($cardId){
$query->where('cars_id', $carId);})->has('cars', '>=', 1)->with('cars')->get();
then obtain cars name via denamic property of a relation
I have some records, i want to get records from them where item is not between given time range, here is my code that i already tried but no success
$other_hour_trade = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->select('finaltrade.*')
->where('finaltrade.user_id', $user_id)
->whereNotBetween('finaltrade.created_at', [DB::raw('exchanges.start_time'), DB::raw("ADDTIME(exchanges.start_time, '01:00:00')")])
->whereNotBetween('finaltrade.created_at', [DB::raw('exchanges.close_time'), DB::raw("SUBTIME(exchanges.close_time, '01:00:00')")])
->get();
'finaltrade.created_at' is a datetime field and
'exchanges.start_time' and 'exchanges.close_time' is a only time field
I have join two tables to get results
I don't know how to make this work directly using whereNotBetween, but since you're already trying to resort to some raw SQL in your current code, why not just use whereRaw instead:
$other_hour_trade = DB::table('finaltrade')
->join('exchanges', 'finaltrade.exchange_id', '=', 'exchanges.id')
->select('finaltrade.*')
->where('finaltrade.user_id', $user_id)
->whereRaw("finaltrade.created_at NOT BETWEEN exchanges.start_time AND ADDTIME(exchanges.start_time, '01:00:00')")
->whereRaw("finaltrade.created_at NOT BETWEEN exchanges.close_time AND SUBTIME(exchanges.close_time, '01:00:00')")
->get();
I have written a Laravel query. I am using whereBetween and orWhereBetween along with a where statement on a column named 'shareable', which should return one row.
But this query does not take where condition into consideration. It took only whereBetween and orWhereBetween. What can be the reason.
my query
$childs = Program::whereIn('id', $programs_by_date)
->where('shareable', '=','1')
->wherebetween('starting_date', [$new_start_date,$new_end_date])
->orwherebetween('ending_date', [$new_start_date,$new_end_date])
->orderBy('starting_date')
->get();
->where('shareable', '=','1') return 0 rows. What can be the reason.
shareable type is enum
You should wrap whereBetween & orWhereBetween in where. Try this:
$childs = Program::whereIn('id', $programs_by_date)
->where('shareable', '=','1')
->where(function($query) use ($new_start_date, $new_end_date){
$query->whereBetween('starting_date', [$new_start_date,$new_end_date])
->orWhereBetween('ending_date', [$new_start_date,$new_end_date]);
})
->orderBy('starting_date')
->get();
Hope this will work.
You Should try this
$child = Program::whereIn('id', $programs_by_date)
->where('shareable', '=','1')
->whereRaw("( starting_date BETWEEN '".$new_start_date."' AND '".$new_end_date."' OR ending_date BETWEEN '".$new_start_date."' AND '".$new_end_date."' ")
->orderBy('starting_date')
->get();
I have this sql (MariaDB) query, it works ok:
SELECT
admin_combustibles.nombre,
admin_combustibles.id_combustible,
admin_combustible_unidades.nombre AS unidades,
admin_tipo_combustibles.nombre AS tipo_combustible,
admin_indice_combustibles.valor_combustible
FROM
admin_combustibles
INNER JOIN admin_combustible_unidades ON admin_combustibles.combustible_unidades_id = admin_combustible_unidades.id_combustible_unidad
INNER JOIN admin_tipo_combustibles ON admin_combustibles.tipo_combustible_id = admin_tipo_combustibles.id_tipo_combustible
LEFT JOIN admin_indice_combustibles ON admin_combustibles.id_combustible = admin_indice_combustibles.combustible_id
AND admin_indice_combustibles.anio = 1992
AND admin_indice_combustibles.mes = 6
ORDER BY
admin_combustibles.nombre
But when I try to make it through Laravel, I have some error because Laravel put some on the number 1992, in that way the query doesn't work.
Plus, I don't know how to do the AND on Laravel, I only have orOn but it doesn't work:
$datos = AdminCombustible::select([
'admin_combustibles.nombre',
'admin_combustibles.id_combustible',
'admin_combustible_unidades.nombre AS unidades',
'admin_tipo_combustibles.nombre AS tipo_combustible',
'admin_indice_combustibles.valor_combustible'])
->join('admin_combustible_unidades', 'admin_combustibles.combustible_unidades_id', '=', 'admin_combustible_unidades.id_combustible_unidad')
->join('admin_tipo_combustibles', 'admin_combustibles.tipo_combustible_id', '=', 'admin_tipo_combustibles.id_tipo_combustible')
->leftJoin('admin_indice_combustibles', function ($join) {
$join->on('admin_indice_combustibles.combustible_id', '=', 'admin_combustibles.id_combustible')->orOn('admin_indice_combustibles.anio', '=', 1992);
})
->get();
dd($datos);
I got an sql syntax error.
Any help on how to make that query with query builder of Laravel? (I put the entire query as DB::raw and it works, but I don't want to use raw() )
I think there might be two problems here. Since you are using and in your original query, you might be needing to use or instead of orOn on your join.
Also you will need to use DB::raw() on the parameters, otherwise Laravel will consider them columns....
$join->on('admin_indice_combustibles.combustible_id', '=', 'admin_combustibles.id_combustible')->on('admin_indice_combustibles.anio', '=', DB::raw('1992'));
I get a SQL in laravel like this
$scheduleMap=array("schedule_id"=>$scheduleId);
$scheduleConsume=DB::connection("mysql_report")->table("xxx")
->where($scheduleMap)
->whereBetween(DB::Raw("TO_DAYS(FROM_UNIXTIME(report_time))"),array(DB::Raw("TO_DAYS('".$startDate."')"),DB::Raw("TO_DAYS('".$startDate."')")))
->select(DB::Raw("SUM(imp_num) as imp_num"))
->first();
and I printed SQL as
select SUM(imp_num) as imp_num from `xxx`
where TO_DAYS(FROM_UNIXTIME(report_time))
between TO_DAYS('2016-11-05')
and TO_DAYS('2016-11-12')
Then I try to run sql in navicat,it works well,but in laravel,it return null.
I can't understand! I have to use whereRaw now.
Try this :)
$scheduleConsume = DB::connection("mysql_report")
->table('xxx')
->where('schedule_id', $scheduleId)
->whereBetween(
DB::Raw("TO_DAYS(FROM_UNIXTIME(report_time))"), [
DB::Raw("TO_DAYS('".$startDate."')"),DB::Raw("TO_DAYS('".$startDate."')")
]
)
->select(DB::Raw("SUM(imp_num) as imp_num"))
->first();