json search using laravel query builder issues - mysql

["php", "css", "Mysql"]
["html", "css", "js"]
["js","css"]
This is value for 'keywords' field in 3 records
I need search result for this
["php","css"]
ie, result should contain the above 3 record as there is 'php' in 1st record and 'css' in other 2 records
SELECT * FROMjob_postsWHERE JSON_CONTAINS(keywords, '["php","css"]')
only giving the 1st record

array:2 [
0 => "php"
1 => "css"
]
Made use of array instead of json_encoded format($request['keywords] itself)
DB::table('job_posts')
->when($keywords, function ($query) use ( $keywords) {
foreach ($keywords as $key => $value) {
$query->orWhere('keywords', 'LIKE', '%' . $value . '%');
}
}
->get();

Related

laravel add multiple where and or where

[
[
[
'condition1',
'value1',
],
[
'condition2',
'value2',
],
[
'condition3',
'value3',
],
],
[
'condition4',
'value4',
],
[
]
]
Im trying to build query builder with values 1 ,values 2, value 3 are in 'or' condition and value 4 in 'and' condition
for first two array i can get the result like what i need
$result = DB::table('table')
->where(function($query) use($value1) {
$query->where('condition1', $value1) // and condition
->orWhere('condition2', $value2) // rest or in or condition
->orWhere('condition3', $value3)
})
->where('condition4', $value4)
->get();
But the array will be keep going. inside the array index 0 is in 'and' condition and a;; other index in or condition
I have tried like
foreach($values as $value){ //
$result->where(function ($qry) use ($value) {
foreach($value as $index=>$val){
$qry->when($index==0),function($qyr){
$qry->where();
}
},function($qry){
$qry->orwhere();
}
});
}
Is there any better solution or improvement i can add?
You should not have condition3 in the grouping query. Normaly it should look like this:
$result = DB::table('table')->where(function($query) use($value1, $value2) {
$query->where('condition1', $value1) // where condition1
->orWhere('condition2', $value2); // or where condition2
})->Where('condition3', $value3) // And where condition3
->get();

Sum query doubles when joining three tables in Laravel

I'm sending data to chartist.js using Laravel controller. When I try to join three tables together to sum the values, the output is essentially doubled when I join the third table.
The following query gets the data I need however doesn't sum them accurately
$chart_stats = Transactions::join('customers', 'customers.id', '=', 'transactions.customer_id')
->join('orders', 'orders.customer_id', '=', 'transactions.customer_id')
->distinct()
->select('customers.region', 'transactions.deposit', 'transactions.purchase_total', 'transactions.finance_amount_paid', 'orders.gov_funding_amount')
->whereIn('customers.region', $selected_regions)
->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
->select(
DB::raw('customers.region as region' ),
DB::raw('sum(transactions.deposit) as deposits'),
DB::raw('sum(transactions.purchase_total) as sums'),
DB::raw('sum(transactions.finance_amount_paid) as finance_paid'),
DB::raw('sum(transactions.deposit+transactions.finance_amount_paid) as total_paid'),
DB::raw('sum(orders.gov_funding_amount) as funding')
)
->groupBy('customers.region')
->orderBy('sums', 'asc')
->get();
This will output the following in an array:
#original: array:6 [▼
"region" => "Region 1"
"deposits" => "5025.40"
"sums" => "52875.00"
"finance_amount_paid" => "0.00"
"total_paid" => "5025.40"
"funding" => "9228.00"
It should be:
#original: array:6 [▼
"region" => "Region 1"
"deposits" => "1706.00"
"sums" => "21271.00"
"finance_amount_paid" => "0.00"
"total_paid" => "1706.40"
"funding" => "3396.00"
I was going to give this as a comment but it would be better as a answer. It's a proposition and I could be wrong. There are 2 possible answers.
Change these lines:
->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
To either:
->whereBetween('transaction.created_at, $from, $to)
Or edit: type, arrays into arrays, corrected:
->where([['transactions.created_at', '>', $from], ['transactions.created_at', '<', $to]])
Methink it is possible, if both conditions are true, the row is selected twice. The distinct() may not do what it is intended to do. You could also try a closure:
->where(function ($query) {
$query->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
->distinct();
})

Getting key value pair array in Yii2

$data = User::find()
->select('id, name')
->where(['status' => 'active'])
->orderBy('id DESC')
->asArray()
->all();
[
[0]=>[
id=>1
name="test"
]
[1]=>[
id=>2
name="test1"
]
]
What I want is array which looks similar to this. Mapping the id with name so it can be accessed and checked.
[
[1]=>'test'
[2]=>'test1'
]
Instead of using the ArrayHelper you can directly achieve the desired output by using indexBy() and column() within your query:
$data = User::find()
->select(['name', 'id'])
->where(['status' => 'active'])
->orderBy(['id' => SORT_DESC])
->indexBy('id')
->column();
indexBy() defines the array key, while column() will take the first column in the select condition as value.
Try this
Add the below namespace and use the arrayhelper of Yii2 to map
use yii\helpers\ArrayHelper
$userdata = ArrayHelper::map($data, 'id', 'name');

search for multiple keywords in the same field in Yii2

I need to search several key words that appear in the same database field. For example if field contains "The quick brown fox jumps over the lazy dog" and someone searches for "quick" and "dog" this should be returned as a match.
so I take the search field and explode it into an array based on spaces:
$terms = explode( " ", $this->search_term );
Then I thought I'd throw this into a loop:
foreach ($terms as $key) {
$query->andFilterWhere( [
'or',
[ 'like', 'item.name', $key ],
] );
}
However this isn't working, plus it's not very elegant.
You should simply build properly the condition parameter, e.g. :
$condition = ['or'];
foreach ($terms as $key) {
$condition[] = ['like', 'item.name', $key];
}
$query->andWhere($condition);
I think you have to join the conditions by using or conditions.
foreach ($terms as $key) {
$query->orFilterWhere( [
'or',
[ 'like', 'item.name', $key ],
] );
}
This is how you have to add another or conditions. See here for further details.
I guess there is no other ways to do this without doing for loop.

Wordpress pods: Exporting specific columns to json

I have the following code for exporting all the items in one of my pods to json. The thing is I don't need all the 130 columns in the json file, but only about 20. Since this will be done for about 150 items I thought I could save some loading time by not printing out all the fields, but I do not know how to do this. For example I only want to print the column value named 'title' for all items in the pod. My code is attached bellow.
<?php
$pods = pods('name', array('orderby' => 'name asc', 'limit' => -1));
$all_companies = $pods->export_data();
if ( !empty( $all_companies ) ) {
die(json_encode($all_companies);
}else{
die(json_encode(array('error' => 'No cars found.')));
}
?>
I thought about doing something like this:
if ( 0 < $all_companies->total() ) {
while ($all_companies->fetch()) {
$json .= $all_companies->field('title');
}
$json = rtrim($json, ",");
$json .= '}}';
}
echo $json;
But it doesn't work and also the code becomes very long.
I'd make an array of the names of the twenty fields you want then build an array of those fields for each item, by doing a foreach of those field names passed to Pods::field() inside the while loop. Like this:
$pods = pods('name', array('orderby' => 'name asc', 'limit' => -1));
$fields = array( 'field_1', 'field_2' );
if ( $pods->total() > 0 ) {
while ( $pods->fetch() ) {
foreach ( $fields as $field ) {
$json[ $pods->id() ] = $pods->field( $field );
}
}
$json = json_encode( $json );
}
Alternatively, you could hack the /pods/<pod> endpoint of our JSON API to accept a list of fields to return as the body of the request. Wouldn't be hard to do, make sure to submit a pull request if you make it work.