Laravel: how to add where clause using query builder? - php

I have this query, made using Laravel query builder:
$rows = DB::table('elements')->where('type', 1);
That corresponds to: "SELECT * from elements WHERE type=1"
Now, in some cases I need to add a second Where to create a query like this:
SELECT * from elements WHERE type=1 AND lang='EN'
Using classic php I'd do something like:
$sql = 'SELECT * from elements WHERE type=1';
if($var==true) $sql .= " AND lang='EN'";
How can I do that using Laravel Query Builder?
Thank you.

You may try something like this
$query = DB::table('elements');
$query->where('some_field', 'some_value');
// Conditionally add another where
if($type) $query->where('type', 1);
// Conditionally add another where
if($lang) $query->where('lang', 'EN');
$rows = $query->get();
Also, check this answer.

$userId = Auth::id();
$data['user_list'] =DB::table('users')->
select('name')->
where('id','!=',$userId)->
where('is_admin','!=','1')->
get();
like that you use multiple where clause :)

Related

Passing laravel eloquent query params dynamically

I have the following query params in string format
$query = '->whereIn('short_code', ["9999"])->whereBetween('request_timestamp', [request('startTime'), request('endTime')])';
How do i pass it to the eloquent? Am trying to achieve something like this
InboundMessage::query()->{$query};
Am getting the error below
Property [->whereIn('short_code', ["9999"])->whereBetween('request_timestamp', [request('startTime'), request('endTime')])] does not exist on the Eloquent builder instance.
The problem with the above query is that it looks like this
InboundMessage::query()->->whereIn('short_code', ["9999"])..
Since you have put -> in both the query builder and the $query string. So just adjust your $query to
$query = 'whereIn('short_code', ["9999"])->whereBetween('request_timestamp', [request('startTime'), request('endTime')])';
It will be something like this (not tested) using raw DB expressions:
$query = DB::table('tableName')
->whereRaw('columnName IN ["9999"] AND columnName BETWEEN value1 AND value2')
->get();

How do I filter my DB query results to not display any duplicate value

I have a query like this:
$blog = BlogModel::select('user_id')->get();
and it return this
[{"user_id":2},{"user_id":3},{"user_id":4},{"user_id":4},{"user_id":6}]
I would like Delete duplicate user_id like this
[{"user_id":2},{"user_id":3},{"user_id":4},{"user_id":6}]
You can use DISTINCT for that purpose
$blog = BlogModel::select('user_id')->distinct()->get();
You can use distinct() to force the query to return distinct results.
Try change this:
$blog = BlogModel::select('user_id')->get();
To:
$blog = BlogModel::select('user_id')->distinct()->get();
You can read more here:
https://laravel.com/docs/9.x/queries
$blog = BlogModel::selectRaw('distinct user_id')->get();

Yii 1 query return incorrect data

I have query:
$listings = Yii::app()->db->createCommand('SELECT * FROM listings')->where(['or like','c_sales_stage',['Needs Refresh','Active']])->andWhere('c_listing_featured_c = 1')->queryAll();
Returns all the listings even where c_listing_featured_c is 0.
What am i doing wrong?
Thanks
As the documentation says:
Note: Query builder cannot be used to modify an existing query specified as a SQL statement. For example, the following code will not work:
$command = Yii::app()->db->createCommand('SELECT * FROM tbl_user');
// the following line will NOT append WHERE clause to the above SQL
$command->where('id=:id', array(':id'=>$id));
To solve your problem remove argument from createCommand() function and add from() in chain:
$listings = Yii::app()->db->createCommand()
->from('listings')
//->where() //here your where condition
->andWhere('c_listing_featured_c = 1')
->queryAll();

Making sql like query using yii2 model

Am trying to perform this query
$command = $connection->createCommand("
SELECT
tbl_checklist.report_val AS item
FROM tbl_checks
LEFT JOIN tbl_checklist ON tbl_checklist.id = tbl_checks.check_id
WHERE truck_id = ".$value->id."
"
);
$results = $command->queryAll();
THe above works but i would like to perform the same using models
So i have tried
$results = TblChecks::find()
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
How do i add the SELECT tbl_checklist.report_val AS item in the Model flow
you should try like this
$results = TblChecks::find()->select(["tbl_checklist.report_val AS item","tbl_checks.*"])
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
Try this way, I hope it will solve your issue.
$results = TblChecks::find()
->select[tbl_checklist.report_val AS item]
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
You should use select() function:
$results = TblChecks::find()
->select('tbl_checklist.report_val AS item')
->leftJoin("tbl_checklist", "tbl_checklist.id = tbl_checks.check_id")
->where(["truck_id"=>$value->id])
->all();
And add property $item in your model.

Eloquent ORM: count() remove the select(...)

I am using Eloquent ORM outside of Laravel-4 and I am building a custom Paginator.
First, I build a query using Fluent Query Builder. I want to get the number of result the query could return using count() and then I do a custom pagination using take(x) and skip(y). I need to do the count() before the take()->skip()->get() so I dont fall outside of the page range. The problem is that when I use the count() method on the query, it seems to remove any select I added previously.
I isolated the problem to this simple example:
$query = DB::table('companies')
->join('countries','companies.country_id','=','countries.id')
->select(
'companies.name as company_name',
'countries.name as country_name'
);
$nbPages = $query->count();
$results = $query->get();
//$results contains all fields of both tables 'companies' and 'countries'
If i invert the order of the count and get, it works fine:
$results = $query->get();
$nbPages = $query->count();
//$results contains only 'company_name' and 'country_name'
Question: is there a more elegant way the using something like this:
$tmp = clone $query;
$nbPages = $tmp->count();
$results = $query->get();
There is not, unfortunately. Open issue on github about the problem: https://github.com/laravel/framework/pull/3416

Categories