Laravel / Mongodb - Remove specifc object form array of objects - php

I have this array ( matching_competitors ) of objects in mongodb:
I want to delete specific object where id_product_competitor value is match.
For example I want to delete object number 2 where id_product_compeitor = 224731
To do that I am using this query :
$delete_to_mongodb = DB::connection('mongodb')
->collection( 'products_' . $id_project)
->where('id', $id_user_product )
->where( 'matching_competitors.id_product_competitor', $product_id )
->unset( 'matching_competitors.$.id_product_competitor');
But the specific object is not deleting :(

Related

query laravel not working if pass variable in Where NOT IN

I'm trying to filter items from a database table
what I do is get the ids that I want to exclude and then through -> whereNotIn in laravel, I pass the ids
$idcontracts=array();
$idbike=array();
$biciCorretta = array();
$findcontract=Contract::whereRaw('? between data_inizio and data_fine', [$datainizio])->whereRaw('? between data_inizio and data_fine', [$datafine])->get();
foreach ($findcontract as $key) {
if (!in_array($key->id,$idcontracts)) {
array_push($idcontracts,$key->id);
}
}
foreach ($idcontracts as $idcontract) {
$bike_contracts=DB::table('bike_contract')->where('contract_id',$idcontract)->get();
foreach ($bike_contracts as $bike_contract) {
if (!in_array($bike_contract->bike_id,$idbike)) {
array_push($idbike,$bike_contract->bike_id);
}
}
}
$notid=implode("', '",$idbike);
up to this point I have no problem.
the result of "implode" gives me the ids I want to remove
this is the result of $idbike and $notid:
this is the query I write to exclude the ids found:
$bikes = Bike::with('category')->whereNotIn('id', [$notid])->orderBy('category_id')->get();
the problem is that it doesn't exclude me the ids passed with $notid
but if I manually pass the ids, it removes them instead:
$bikes = Bike::with('category')->whereNotIn('id', [40,41,34,36,39])->orderBy('category_id')->get();
am I doing something wrong?
You shouldn't implode $notid, that makes it a string and Laravels whereNotIn() already does that for you.
->whereNotIn('id', $idbike)
And remove the $notid parameter, as it is not needed.
implode will return in string, and because of that it will not work correctly, you should pass it as array instead.
If you print data
$idbike =[40,41,34,36,39];
print_r($idbike);
Output will be Array
Array
(
[0] => 40
[1] => 41
[2] => 34
[3] => 36
[4] => 39
)
and if you print below code
$notid=[implode(",",$idbike)];
print_r($notid);
The output will be
Array
(
[0] => 40,41,34,36,39
)
So your query become
->whereNotIn('id', ["40,41,34,36,39"])
so laravel searching for id of "40,41,34,36,39". so its not returning result
So you can pass array directly to wherenotin
->whereNotIn('id', $idbike)
Laravel, whereNotIn method removes elements from the collection that have a specified item value that is contained within the given array. That means you have to pass an array
So, idbike is the array you mentioned
$bikes = Bike::with('category')->whereNotIn('id', idbike)->orderBy('category_id')->get();

Laravel - how to group data by key and save to array?

I have table attribute_values(id, value, attr_group_id).
I need to return the collection grouped by key attr_group_id.
in clear php using ORM RedBean i made:
$data = \DB::table('attribute_values')->get();
$attrs = [];
foreach ($data as $k => $v){
$attrs [$v['attr_group_id']][$k] = $v['value'];
}
return $attrs;
I need same using Laravel, after this one:
$data = \DB::table('attribute_values')->get();
My table
id value attr_group_id
1 one 1
2 two 1
3 three 2
4 four 2
5 five 3
6 six 3
And i need result
Array(
[1] => Array
(
[1] => one
[2] => two
)
[2] => Array
(
[3] => three
[4] => four
)
[3] => Array
(
[5] => five
[6] => six
)
)
Fetch all data, and map it with attribute id of every row will work,
$data = \DB::table('attribute_values')->get();
$attrs = [];
foreach ($data as $key => $value) {
// -> as it return std object
$attrs[$value->attr_group_id][] = $value->value;
}
dd($attrs);
You can use the groupBy() function of collection as:
$data = \DB::table('attribute_values')->get()->groupBy('attr_group_id');
It merges records with same attr_group_id under this field's value as making key of the collection.
Doing all this in raw SQL will be more efficient, SQL database are quite good at these operations. SQL has a group by function, since you are overwriting value, i just get it out with max() (this seems weird, that you overwrite the value, do you actually just want unique results?).
DB::table('attribute_values')
->select('attr_group_id', DB::raw('max(value)'))
->groupBy('attr_group_id')
->get();
EDIT
Since the scope has changed, you can utilize Laravels Collection methods, that is opreations on a Collection.
DB::table('attribute_values')
->get()
->groupBy('attr_group_id')
->toArray();
Friends, this is a ready task that I needed !
I did it myself and you helped me. If anyone interested can read.
I'll explain to you why I needed this particular method. I am doing an online store with a clock and now there was a task to make filters and attributes for filters.
So there are three tables
attribute_groups table
attribute_products table
attribute_values
I need to display the Laravel widget on my .blade.php like as
{{ Widget::run('filter', 'tpl' => 'widgets.filter', 'filter' => null,]) }}
When i creating a new product in the admin panel.
I must to save the product id and attribute_id in attribute_products, but there can be as many attributes as possible for one product. so, if I'll use this option
$data = \DB::table('attribute_values')
->get()
->groupBy('attr_group_id')
->toArray();
I got result:
But! each new array starts with index 0. But I need an index that means its id. attr_group_id from table attribute_value for saving into attribute_products.
And after I see only one method for me.
$data = \DB::table('attribute_values')->get();
$attrs = [];
foreach ($data as $key => $value) {
$attrs[$value->attr_group_id][$value->id] = $value->value;
}
return $attrs;
and the result I was looking for
now you can see what's the difference and what was needed. Array index starts 1,2,3,4,5 and this index = attr_group_id. Unfortunately I could not initially ask the right question. thanks to all.
Laravel Version 5.8
So You need to Group the id
if You need in the Model Way I have created the Model as AttributeValue
$modelWay = \App\AttributeValue::get()
->groupBy('attr_group_id');
if You need in the DBWay I have created the table as attribute_values
$dbWay = \DB::table('attribute_values')
->get()
->groupBy('attr_group_id');
Both Will give the Same Result

Laravel 5.3 cannot use select value from collection

Im trying to calculate the price including tax of a product in an ecommerce app. In table tax i have the following columns:
id - iso_code - vat.
My query to obtain vat information for a particular countryid:
$taxRate = DB::table('tax')
->select('vat')
->where('iso_code', $productcountryid)
->get();
If I print_r the $taxRate value I obtain
Illuminate\Support\Collection Object ( [items:protected]
=> Array ( [0] => stdClass Object ( [vat] => 1 ) ) )
To retrieve vat value I used:
$taxRates=$taxRate[0]['tax'];
and I obtain the following info:
Cannot use object of type stdClass as array
On the other hand, using
$taxRates = $taxRate->vat;
Error: Undefined property: Illuminate\Support\Collection::$vat
My idea is to use $taxRate value to obtain a simple calculation
priceamount = $productprice * $taxRate
UPDATE using #assada suggestion ------
$array = $taxRate->toArray();
(array)[0]['vat']
gives error:
Cannot use object of type stdClass as array
any help appreciated about how to process the value returned in a collection.
brgds.
https://laravel.com/docs/5.4/collections
You can use some like this:
$taxRate = DB::table('tax')
->select('vat')
->where('iso_code', $productcountryid)
->get();
$collection = collect($taxRate);
$array = $collection->toArray();
or just try
$taxRate = DB::table('tax')
->select('vat')
->where('iso_code', $productcountryid)
->get();
$array = $taxRate->toArray();

How to read data from an array containing object within him

Im having a hard time to read some data that i get from joomla 2.5. First i have created a module that stores data on DB as a json. So first i read from DB linke:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('params')));
$query->from($db->quoteName('#__modules'));
$query->where($db->quoteName('module') . ' = '. $db->quote('mod_products'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
and the result that i get as an array that contain objects, and each object has json data.
below is the arrray that i get from the query:
Array
(
[0] => stdClass Object
(
[params] => {
"product_name":"Sangiovese",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"1"
}
)
[1] => stdClass Object
(
[params] => {
"product_name":"Syrah",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"0",
}
)
[2] => stdClass Object
(
[params] => {
"product_name":"Merlot",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"Red",
"isvisible":"0"
}
)
[3] => stdClass Object
(
[params] => {
"product_name":"Vermentino",
"product_subtitle":"Maremma Toscana DOC",
"product_category":"White",
"isvisible":"0"
}
)
);
So what i want to do is to access the data within each param for examle:
PS: Array name is $results.
,
EX: i want to access product_name of each of the products that are on this array, or subtitle and so on.
so i did something like this, but its not working, i know i am not doing it right, but i hope someone can help me, and i would really appruciate it.
foreach( $results as $result )
{
echo $result->prams->product_name;
}
Error that shows when this code gets executed:
Notice: Trying to get property of non-object in
I really would need some advice on this.
Thank you!
Every item in your list is an object:
[0] => stdClass Object
[1] => stdClass Object
And every object has a params property which is a string containing JSON data.
You need to use json_decode built-in function to convert JSON string to an object or array.
Try this approach:
$paramsDecoded = json_decode($result->params, true);
print $paramsDecoded['product_name'];
Hello and thanks to all who helped,
I managed to make it functional.
So im gonna post here all the code for everyone else that passes on the same waters and needs help.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('params')));
$query->from($db->quoteName('#__modules'));
$query->where($db->quoteName('module') . ' = '. $db->quote('mod_products') .' AND '. $db->quoteName('language') . ' <> '. $db->quote('en-GB'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
$count = count($results);
What i did to make the functionality i needed:
for ($i=0; $i < $count; $i++) {
$json = $results[$i]->params;
$product = json_decode($json);
// code here, example
echo $product->product_subtitle;
}
So, yes. I needed to decode using json_decode first, before using it on other parts of the code.
Thanks for helping. Hope this posts helps other developers who same as me, will have difficulties working with the way Joomla manipulates objects stored in database.

Codeigniter & Datamapper: Retrive all the ID's from ID column and attach to array

I am having trouble collecting all the ids from the ID column. What the code above does is getting only one ID, at least it goes to the array but I want to take all of them.
$getArticlesId = new Article_model();
$getArticlesId->select('id');
$getArticlesId->get();
$anarray = $getArticlesId->to_array(array('id'));
That returns:
SELECT articles.id
FROM (articles)
and Array ( [id] => 43 ) , but there must be 10 more
What I am doing wrong ?
to_array() generates an array with your specified field(s). all_to_array() generates multiple arrays with your specified id field. $anarray[0]['id'] should be your first id. Hope this is what you're looking for.
This should work:
// RETURN ORM OBJECT
$getArticlesId = new Article_model();
$getArticlesId->select('id');
$getArticlesId->get_iterated();
$getArticlesId_Total = $getArticlesId->result_count();
// -------- EOF - RETURN ORM OBJECT
// GENERATE PHP ARRAY FROM OBJECT
if ($getArticlesId_Total > 1)
{
$anarray = $getArticlesId->all_to_array();
}
// -------- EOF - GENERATE PHP ARRAY FROM OBJECT
You may also want to try all_to_single_array().
http://datamapper.wanwizard.eu/pages/extensions/array.html

Categories