Laravel query join on not null - mysql

I have the following query join in MySQL.
left join the_fields as tf on
tf.tf_kode = x.tf_kode
and tf.is_payed is not null
I tried to convert to laravel query builder like this:
->leftJoin('the_fields as tf', function ($j) {
$j->on('tf.tf_kode', '=', 'x.tf_kode');
$j->on('tf.is_payed','!=', null);
})
But it shows the error unknown column '' on clouse.
Please help. Thanks!

->on method arguments are columns and operators, You cant pass where condition in it.
You can use this:
->leftJoin('the_fields as tf', function ($j) {
$j->on('tf.tf_kode', '=', 'x.tf_kode')->whereNotNull('tf.is_payed');
});
Hope this helps you

Related

Rewrite MYSQL query using Laravel query builder

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 ;)

Convert mysql query with left join into Eloquent

I have a mysql query like this:
select result.*, rank_text.text
from cache_user_challenge_result result
left join rank_text on result.rank
between rank_text.rank_from and rank_text.rank_to
Now I want to change this to eloquent for my laravel project, I tried this but it's not work:
$this->select(
"{$this->table}.user_id",
'rank_text.text'
)
->leftJoin('rank_text', "{$this->table}.rank")
->whereBetween("{$this->table}.rank", ['rank_text.rankFrom', 'rank_text.rankTo'])
->first();
Can you tell me what's wrong with this?
Thank you very much!
Update:
After a lot of hours, I change my query to this:
$this->select(
"{$this->table}.user_id",
'rank_text.text'
)
->leftJoin('rank_text', function($query) {
$query->whereBetween("{$this->table}.rank", ['rank_text.rank_from', 'rank_text.rank_to']);
})
->get();
But it's only can get user_id, not the text.
Try to create cache_user_challenge_result model Like
class CacheUserChallengeResult extends Model {
protected $table = 'cache_user_challenge_result';
public function scopeGetCacheUserRank()
{
return static::select(DB::raw('cache_user_challenge_result.*,rank_text.text'))->leftJoin('rank_text', function($join) {
$join->on('cache_user_challenge_result..rank', '=', 'rank_text.rank')->whereBetween('cache_user_challenge_result.rank',['rank_text.rankFrom', 'rank_text.rankTo']);
});
}
}
In Controller You can call like this
CacheUserChallengeResult::getCacheUserRank()->get();
It will provide you the collection for the rank you desire, also you can pass param for which rank you want in range

Laravel multiple Modles query

hey i have looked at quite a few articles now but i think my knowledge hinders me from adapting any example so here i am, hoping you can help:
What i want: Have an eloquent query which looks in 2 tables
What i have:
$myProfile = \App\User::with('friends')->where('friend_type','2')->get();
is my wished for result.
In my User Model i have the following:
public function friends()
{
return $this->hasMany(Friend::class);
}
and in my friends model:
public function user()
{
return $this->belongsTo(User::class);
}
also what i have tried, too:
$myProfile = \App\User::with(['friends'])->where('friend_type','2')->get();
or
$myProfile = \App\User::with('friends')->where('friends.friend_type',2)->get();
but the error i receive remains the same:
Column not found: 1054 Unknown column 'friends.friend_type' in 'where clause' (SQL: select * from `users` where `friends`.`friend_type` = 2 and `users`.`deleted_at` is null)
thanks very much in advance
If you want to select all users whose friend_type is 2 then you should use whereHas. It would be like
\App\User::whereHas('friends', function($q){
$q->where('friends.friend_type',2)
})->get();
I think the following would to the trick:
User::with(['friends' => function ($query) {
$query->where('friend_type', 2);
}])->get();

Use `AND` in Laravel Query Builder, syntax error (orOn)

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'));

Laravel between clause returning null

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();