Passing laravel eloquent query params dynamically - php

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

Related

WhereIn Inside ->where() array - Laravel Query Builder

I'm trying use a whereIn inside a where array I am passing to Laravel query Builder:
$where = [['Participants.Client_Id','IN', $clientId]];
DB::table('Participants')->where($where)->get()
Something like is what I want to achieve, and I know there are works around such as using whereIn, but I'm sharing here a small piece of code to give you an idea, so I need to change the array to make it works as a whereIn, not changing the ->where to ->whereIn or ->whereRaw
DB::table('participants)->whereIn('Participants.Client_Id',$clientId)->get();
You must collect the IDs in the $clientId variables.
If I understand, you could do something like that :
$wheres = [['Participants.Client_Id','IN', [$clientId]]];
$query = DB::table('Participants');
foreach($wheres as $where) {
$query->where($where[0], $where[1], $where[2]);
}
$participants = $query->get();
As laravel document , you can use array in where and each element of this array must be a array with three value . So your $where variable is correct.
But as I searched in operator is not supported by query builder of where.

Yii2 How to get all values from column (DB)

I've been sitting for hours trying to find how to get values from table's iab_categories column category_name. I've found only the way to echo all table names:
$connection = Yii::app()->db;//get connection
$dbSchema = $connection->schema;
//or $connection->getSchema();
$tableNames = $dbSchema->getTableNames();//returns array of tbl schema's
var_export($tableNames);
Can anyone help me?
You can use query builder to do that:
$categories = (new \yii\db\Query())
->select(['category_name'])
->from('iab_categories')
->column();
The select() method sets what columns should be included in result.
The from() method sets what table should be queried.
And the column() method executes the query and return first column from result set as array.
EDIT: now, I've realized that even though you've mentioned Yii 2 in title the code you've included in question looks more like Yii 1.x.
So there is query builder version for Yii 1.x:
$categories = Yii::app()->db->createCommand()
->select('category_name')
->from('iab_categories')
->queryColumn();

Data comparison in laravel

I'm beginner in laravel and I'm trying to run comparison queries given in the database.
I saved a field date that is implemented by a form together with other fields including the name.
I tried to query the name and it works all regularly with this code below.
I would like to retrieve all the rows that have the name variable as the field name that I pass (and here it seems to work) and then only those with the field date that have the specified month at the number that I pass as variable $month.
what would be the right form to do this?
thanks
Piero
public function filterparamenter(){
$name = request('name');
$month = request('$month');
$query = subagente::all();
$query = $query->where('subagente', $subagente);
$query = $query->whereMonth('data', $month)->get();
Method Illuminate\Database\Eloquent\Collection::whereMonth does not exist.
Using ::all() returns a Collection, which has a ->where() method, but ->whereMonth() is only available on Eloquent's Builder class. Change your code as follows:
$query = subagente::query();
$query = $query->where('subagente', $subagente);
$query = $query->whereMonth('data', $month)->get();
Or, more compact:
$results = subagente::where("subagente", $subagente)
->whereMonth("data", $month)
-get();
Using ::query() or ::where() to start your query will generate a Builder instance, which you can chain addition clauses (->where(), ->whereMonth(), etc) on before calling ->get() to return a Collection of subagente records.
Side note, should "data" be "date"?

Laravel: how to add where clause using query builder?

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

PHP Doctrine toArray problem

I have a problem with the toArray() method in Doctrine. Its doesn't get my relations:
First query :
$q = Doctrine::getTable('posts')->find(1);
debug($q->toArray(true));
Print the postid=1 with out the relations
$q = Doctrine::getTable('posts')->find(1);
$q->Tags->toArray();
debug($q->toArray(true));
...prints the results with tag relation.
But i want to do:
Doctrine::getTable('posts')->findAll()->toArray(true);
...and get all of relations of posts , instead I got an array of post row.
Any idea about how to make it work with the relations?
(notice i added toArray(true) for deep property.
thanks for any help
You could create named query for this table with all relations attached:
Doctrine::getTable('posts')->addNamedQuery('get.by.id.with.relations', 'DQL here...');
And then just use something like this:
Doctrine::getTable('posts')->find('get.by.id.with.relations', array(123));
I beleive you need to do a Join with the query. Otherwise it doesnt hydrate the realated data.
$q = Doctrine_Query::create()
->from('Post p')
->leftJoin('p.RelatedModel1 rm1')
->leftJoin('p.RelatedModel2 rm2');
$q->findAll()->toArray(true);
$q = Doctrine_Query::create()
->from('Post p')
->leftJoin('p.RelatedModel1 rm1')
->leftJoin('p.RelatedModel2 rm2');
$q->findAll()->toArray(true);
Can i Add ->limit()->offset()
to the query ?
I guss that if i first create the query then findAll will act the same as execute right ?

Categories