Laravel DB::table AND statement? - php

I'm very new to Laravel and don't quite understand the DB::table method in conjuction with an AND clause.
So I have this query at the moment:
$query = DB::select( DB::raw("SELECT * FROM tablethis WHERE id = '$result' AND type = 'like' ORDER BY 'created_at' ASC"));
It is working, but I'd like to use Laravel's Query Builder to produce something like:
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
But this seems to ignore the second where() completely. So, basically how do I make this work?

Just adding another ->where behind another ->where is the way to get another where statement
So your code should be fine.
$query = DB::table('tablethis')->where('id', '=', $result)->where('type', '=', 'like')->orderBy('created_at', 'desc')
There must be something wrong with a different part.
I do hope this isn't your full query.
If it is, you need a ->get() at the end.

For sure this code should work as expected.
I don't know how you check the query executed, but you can go to app/providers/EventServiceProvider.php (I assume you have L5) and in boot method add:
Event::listen(
'illuminate.query',
function ($sql, $bindings, $time) {
$sql = str_replace(array('%', '?'), array('%%', "'%s'"),
$sql);
$full_sql = vsprintf($sql, $bindings);
file_put_contents(storage_path() . DIRECTORY_SEPARATOR .
'logs' . DIRECTORY_SEPARATOR . 'sql_log.sql',
$full_sql . ";\n", FILE_APPEND);
}
);
to see exact SQL that was executed.
In addition (but it's just improvement) when using = operator, you can omit it, so you can use here:
$query = DB::table('tablethis')->where('id', $result)->where('type', 'like')->orderBy('created_at', 'desc');

Related

Implementing an or where condition in yii2 find

Am performing a find() in yii2 I understand that there can be andwhere but what of orWher
I have tried
$query = Tblpr::find()->where(['PRID'=>2])->andwhere(['new'=>1])->all();
How can i implement orWhere
Using Where OR
$query = Tblpr::find();
$query->andFilterWhere(['or',
['PRID',2],
['new',1]
])->all();
OR
$query = Tblpr::find()->select('*')
->orWhere(['PRID'=>2,'new'=>1])->all();
You can also use createCommand
$query = (new \yii\db\Query())
->select('*')
->from('Tblpr') // put your table name here
->where(['PRID'=>[2]])
->orWhere(['new'=>[1]]);
$command = $query->createCommand();
print_r ($command->sql);die;
The following should work for a query with ->where() and ->orWhere()
$query = Tblpr::find()
->where(['PRID' => 2])
->orWhere(['attribute' => 'value'])
->all();

How to use one query for different selects in laravel?

I thought it would be a good idea to define a query and use it for several selects or counts later, but it does not work. The second select has both wheres in the sql statement:
$query = Pic::where('pics.user_id',$user->id);
if($cat) $query->where('cat',$cat);
if($year) $query->where('jahrprod',$year);
$zb = $query->select('pics.id','pics.title','pics.created_at')
->where('pics.id', '>', $pic->id)
->orderBy('pics.id')
->take(2)
->get()->reverse();
$za = $query->select('pics.id','pics.title','pics.created_at')
->where('pics.id', '<', $pic->id)
->orderBy('pics.id')
->take(13)
->get();
Query:
SELECT `pics`.`id`, `pics`.`title`, `pics`.`created_at`
FROM `pics`
WHERE `pics`.`user_id` = '3'
AND `pics`.`id` > '2180'
AND `pics`.`id` < '2180'
ORDER BY `pics`.`id` ASC, `pics`.`id` ASC
LIMIT 13
I tried to "pass it as reference" i.e. &$query->select... but "only variables can be passed as reference".
How can I use the query , or save it, and use it for both actions. Is it possible?
You are updating object state with the statements when you do $query->where(), so yeah, when you're doing a second select, all conditions from the first one are still there. Thats the reason why these lines work without any assignments:
if($cat) $query->where('cat',$cat);
if($year) $query->where('jahrprod',$year);
To achieve described behaviour you would need to create an query object copy:
$query = Pic::where('pics.user_id',$user->id);
if($cat) $query->where('cat',$cat);
if($year) $query->where('jahrprod',$year);
$queryClone = clone $query;
$zb = $query->select('pics.id','pics.title','pics.created_at')
->where('pics.id', '>', $pic->id)
->orderBy('pics.id')
->take(2)
->get()->reverse();
$za = $queryClone->select('pics.id','pics.title','pics.created_at')
->where('pics.id', '<', $pic->id)
->orderBy('pics.id')
->take(13)
->get();
Notice that mere assignment would not work here:
$queryClone = $query;
Because that would pass object reference and would result in the same behaviour as in your case. Clone creates a full object copy.
http://php.net/manual/en/language.oop5.cloning.php

Laravel-5 'LIKE' equivalent (Eloquent)

I'm using the below code to pull some results from the database with Laravel 5.
BookingDates::where('email', Input::get('email'))->orWhere('name', 'like', Input::get('name'))->get()
However, the orWhereLike doesn't seem to be matching any results. What does that code produce in terms of MySQL statements?
I'm trying to achieve something like the following:
select * from booking_dates where email='my#email.com' or name like '%John%'
If you want to see what is run in the database use dd(DB::getQueryLog()) to see what queries were run.
Try this
BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
I have scopes for this, hope it help somebody.
https://laravel.com/docs/master/eloquent#local-scopes
public function scopeWhereLike($query, $column, $value)
{
return $query->where($column, 'like', '%'.$value.'%');
}
public function scopeOrWhereLike($query, $column, $value)
{
return $query->orWhere($column, 'like', '%'.$value.'%');
}
Usage:
$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
I think this is better, following the good practices of passing parameters to the query:
BookingDates::whereRaw('email = ? or name like ?', [$request->email,"%{$request->name}%"])->get();
Better:
BookingDates::where('email',$request->email)
->orWhere('name','like',"%{$request->name}%")->get();
You can see it in the documentation, Laravel 5.5.
You can also use the Laravel scout and make it easier with search.
Here is the documentation.
the query which is mentioned below worked for me maybe it will be helpful for someone.
$platform = DB::table('idgbPlatforms')->where('name', 'LIKE',"%{$requestedplatform}%")->first();
If you wish to use it on controller you can do something like:
$generatequery = 'select * from blogs where is_active = 1 and blog_name like '%'.$blogs.'%' order by updated_at desc, id desc';
$blogslists = DB::select($generatequery);
If you are using Postgres, The key word ILIKE can be used instead of LIKE to make the match case-insensitive according to the active locale. This is not in the SQL standard but is a PostgreSQL extension.
this worked for me.
User::where('name, 'ILIKE', $search)->get();
postgres documentation

laravel using query builder without chaining

I have a query builder that works:
$article = Page::where('slug', '=', $slug)
->where('hide', '=', $hidden)
->first();
But I want to only add the second where statement if hidden is equal to 1. I've tried the code below which shows the logic of what I'm trying to do, but it doesn't work.
$article = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$article->where('hide', '=', 1);
}
$article->first();
I'm using Laravel 4, but I think the question still stands with Laravel 3.
Yeah there's a little "gotcha" with Eloquent and the query builder. Try the code below ;)
$query = Page::where('slug', '=', $slug);
if ($hidden == 1) {
$query = $query->where('hide', '=', 1);
}
$article = $query->first();
Note the assigning of $query within the conditional. This is becuase the first where (statically called) returns a different object to the query object within the conditional. One way to get around this, I believe due to a recent commit, is like so:
$query = Page::where('slug', '=', $slug)->query();
This will return the query object and you can do what you want as per normal (Instead of re-assigning $query).
Hope that helps.

Query building using Kohana Query Builder

If I got this:
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->execute()->as_array();
For normal, dsiplaying all orders date_created. Now I can filter by user, doing this ?user_id=112
This will make me having this:
if(isset($get['user_id']))
{
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->where('user_id', '=', $get['user_id'])
->execute()->as_array();
}else{
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->execute()->as_array();
}
Although this is no problem for me have this, but this get to be real much ugly code when I have 4 params to filter out from(4 where statements) e.g ?user_id=112&quantity=2&...
Can I somehow make a inline if/action statement, which would grab all user_ids if there's nothing in $get['user_id'] ?
So I can end up having only this:
$result =
DB::select(
'orders.date_created'
)
->from('orders')
->where('user_id', '=', (isset($get['user_id']) ? $get['user_id'] : 'GRAB ALL!'))
->execute()->as_array();
or is there another, even better way to do this?
Tried looking in Kohana docs if there's some ->if()->where()->exitif().. (just some imagination of how it could work)
You can modify Query object before executing:
$query = DB::select()->from(...);
if (isset($get['user_id'])) {
$query->where('user_id', '=', intval($get['user_id']));
}
if (isset($get['quantity'])) {
$query->where('quantity', '=', floatval($get['quantity']));
}
$result = $query->execute()->as_array();

Categories