I have in my database a column which store a json and I would like to recover the value of a certain object of my json in order to test it
So my column "JSON" contains that
{
"type":"index",
"data ":{"index":2}
}
And if i receive 2, i need to get this column which contain the index 2 to delete it
I have tried this:
$column = Table::where('JSON["data"]["index"]','=', '2' )
->first();
Table::dropColumn($column);
But it doesn't work, beacause i can't get the index
If you are using latest laravel version then,
$column = Table::where('JSON->data->index','2')->first();
Should work.
You can refer official laravel documentation for json where clause here.
Simply use SQL Like
->where('JSON', 'like', '%"index": "2"%');
Since you gave JSON value as a string, it was unable to get the index value.
Can you please try like below,
$column = Table::whereRaw(JSON["data"]["index"], '=', '2' )
->first();
Table::dropColumn($column);
Related
In my MongoDB, I have stored value as below,
{
"_id" : ObjectId("5bed3f5019f0431be000412b"),
"reference" : "SL2PR01MB2745E4160158C08C4B7A367285C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com,SL2PR01MB274333160158C08C4B7A367285C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com",
"email_thread_id" : NumberInt(5)
}
{
"_id" : ObjectId("5bed3f5019f0431be000412b"),
"reference" : "SL2PR01MB2745E4160158C08C4B7A364444C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com",
"email_thread_id" : NumberInt(6)
}
My search keyword is:
"SL2PR01MB2745E4160158C08C4B7A364444C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com"
Which is match with second array from above JSON.
This is my query,
$referanceId= "SL2PR01MB2745E4160158C08C4B7A364444C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com";
$mailExists = DB::connection('mongodb')->collection('email_message')
->select('email_thread_id');
if ($referanceId) {
$mailExists->whereRaw("find_in_set(".$referanceId.", reference)");
}
$query = $mailExists->first();
But it gives me error like below:
ServerException in Find.php line 299:
$or/$and/$nor entries need to be full objects
Please help me to resolve this issue. Thank you.
You can do this easier with the laravel where method, this will do the comparison you want, and also make your code better readable.
You can use the following query to accomplish this:
DB::connection('mongodb')->collection('email_message')
->where("reference", $referanceId)->first();
If your value contains multiple reference id's as a string you can use:
$regexQuery = '/.*'.$referanceId.'.*/';
DB::connection('mongodb')->collection('email_message')
->where("reference", 'regexp', $regexQuery)->first();
This will match the referenceId in any position in the string.
As #hetalgotel mentioned in the comments another query for this is:
$mailExists->where("reference", 'like', "%$referanceId%")
This one produced the expected result in this scenario
I have this following Yii 2 query
$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();
So imagine this query was an array. Everything found by this query has an "id" attribute.
Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.
Currently, I'm using this code.
foreach ($find as $t) {
$arr[] = $t->id;
if ($t->id == $id) {
break;
}
}
$key = count($arr);
return $key;
However, this code is vany wayow on a 100k+ result query.
Is there anyway to speed this up?
You could get the result as an array (instead of object) as
$find = People::find()->where(['c_id' => $c_id])
->orderBy('totals DESC, id DESC')
->asArray()
->all();
then you could find your value using array_search()
$my_index = array_search($id,$find);
but for 100k+ you should find using a direct select in db...instead tha looping on php or load all in php and scan with array_search()
To get array from query in YII, you can use queryAll();
$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->queryAll();
OR, another way to convert the object into an array is:
$find = json_decode(json_encode($find), true); // to convert all data into array.
And once you get results in array, you can implement the actual code for your requirement as given below.
You can use array_search() function to get index of your value.
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
The array_search() function search an array for a value and returns the key.
Maybe I didn't understand you correctly but I assume that you are trying to detect the index or key for your desired id inside an array returned from an SQL query that is sorted by some other column like total.
So let us fetch records from the database with your query with a little change asArray() like this
$find = People::find()
->where(['c_id' => $c_id])
->orderBy('totals DESC, id DESC')
->asArray()
->all();
in the result, let us assume the People table returns you an array with the following dataset ordered by columns total and id DESC.
[
0 => [
'id' => 2 ,
'c_id'=>2,
'name' => 'John' ,
'age'=>18,
'totals'=>100,
],
1=>[
'id'=>1,
'c_id'=>55,
'name'=>'Bob',
'age'=>20,
'totals'=>80,
],
2=>[
'id'=>3,
'c_id'=>85,
'name'=>'Peter',
'age'=>15,
'totals'=>75,
]
];
Now if you look into \yii\helpers\ArrayHelper you will find ArrayHelper::getColumn().
Let us use this on the array we received from the query, I assume that you are searching $id inside the column id so we will first filter out the id column like below.
$idsArray = ArrayHelper::getColumn($find, 'id');
this will give us the ids in the following sequence which is in the same order as the initial result set.
[2,1,3]
then lets use the built-in php function array_search()
$key=array_search($yourId,$idsArray);
Hope this is what you are looking for.
I am using laravel framework but in this WhereBetween not working. i am using price range where price starts form 1 to 500. when i set price 1-100
it gives me all the records that is in beetween 1 to 100 i.e. 20,40,50 etc. When i change the value from 1- 150 the above result will not be displayed it gives me no result(20,40,50). Can anyone help me . Here is my Code
enter code here
$products = Product::with("productimages")
->whereBetween('price',[$data['from'], $data['to']])
->get();
Note:- $data['from'] start value i.e 1 and $data['to'] end value i.e 150 or more
I just had the same issue. When the data type of the value is not an integer, it will behave very unpredictably. So the solution is to either change the datatype of the column or cast it while fetching, like this:
$from = $data['from'];
$to = $data['to'];
$products = Product::with("productimages")
->whereRaw("CAST(price AS UNSIGNED) BETWEEN ${from} AND ${to}")
->get();
I actually had this issue on the PostgreSQL jsonb data type, as it always returns nested values as strings, and between fetching doesn't work properly.
Using Where Between
$projects = Product::where('created_at', '>', $data['from'])
->where('created_at', '<', $data['to'])
->get();
OR
$current = Product::with("productimages")
->whereBetween('created_at', array($data['from'], $data['to']))->get();
OR
DB::table('Product')->whereBetween('created_at', array($data['from'], $data['to']))->get();
I'm querying DB in laravel 4 but can't access the returned value here is the code :
public static function getCityIdByName($cityname){
$cityid = DB::select( DB::raw(" SELECT id FROM cities WHERE match(city_name) against('*" .
$cityname . "*' IN BOOLEAN MODE ) " ));
return $cityid;
}
so the function returns this [{"id":1}] and I need to get value "1", I tried $cityid->id and $cityid['id'] and $cityid[0] but it all returns an error , also it is not a string , when I echo it, it complains that array is not a string Array to string conversion
I solved the problem with this code :
return $cityid[0]->id;
thanks to # Sylwit
Even if it works you can improve it
If you have several results you would take only the first of the array while you would maybe take care of all results.
You can also use ->first() in your query to get only the first object which will avoid you to use the [0].
An interesting link
https://laracasts.com/discuss/channels/eloquent/is-this-match-against-using-relevance-possible
The mysql has table 'subscribe' table and it's as follows:
column type
id int
condition json
type_id id
and the example as follows:
"id": "1",
"condition": "{\"id\":\"2\",\"class\":\"master\",\"zone\":\"west\",\"price\":\"511\"}",
"type_id": "1"
and I want to select the column which match in the column condition like "zone"="west"
the laravel 5.2 has support the order
$subscribe = DB::table('subscribe')->where('condition->class', 'master')->get();
Error
Column not found: 1054 Unknown column 'condition->class' in 'where clause'(
SQL: select * from `subscribe` where `condition->class` = master)
I need is get the term which match the condition where conditon->class = master .I need to select the data which match the need in the model.
I don't know what's wrong. Any help would be much appreciated.
I believe the correct syntax is:
$subscribe = DB::table('subscribe')->where('condition->"$.class"', 'master')->get();
See the example below this paragraph, on https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html
column->path
In MySQL 5.7.9 and later, the -> operator serves as an alias for the JSON_EXTRACT() function when used with two arguments, a column identifier on the left and a JSON path on the right that is evaluated against the JSON document (the column value). You can use such expressions in place of column identifiers wherever they occur in SQL statements.
The thing is the where clause in query is considering as a column name in condition->class and not as a laravel code. you want to extract the value from json. but the query doesn't understand that.
What you need to do is pass entire table as it is in json format to the view and then extract in the view.
I suggest do something like this :
Here, $subscribe has entire table in json . which you can access it by :
$subscribe = DB::table('subscribe')->all();
return response()->json(array('subscribe' => $subscribe));
Then in the view do:
#if($subscribe->condition->class == 'master')
id : {{ $subscribe->id }}
type id : {{ $subscribe->type_id }}
#endif
Updated Code
//get condition in json
$subscribe = DB::table('subscribe')->select('condition')->get();
then,
// convert json to array
$subscribe_array = json_decode($subscribe, true);
// create a new collection instance from the array
$collection_array = collect($subscribe_array);
if($collection_array['class'] == 'master')
{
//do something
}
Something like this do the trick