I have this sorted array with top 5 products
foreach ($bestsellers as $item) {
$data = json_decode($item->order_details, true);
$product_ids[] = key($data);
}
arsort($product_ids);
$three = array_unique(array_slice($product_ids, 0, 5, true));
print_r($three);
The result is
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
1,2,3,4,5 are products id's. Is it possible to use this values in the query to products table so I can display on page more information about the products. Not just the ID.
Something like
Product::where('product_id', $value);
Update
$best = Product::whereIn('product_id', $three)->get();
foreach($best as $info)
{
dd($info->title);
}
Yes, You should use whereIn for array. In fact, whereIn takes second parameter as array of values for specified column.
Product::whereIn('product_id', $value);
whereIn()
The whereIn method verifies that a given column's value is contained
within the given array:
Related
Issue:
Laravel GeoChart Library to Render Google Visualization -> AddRow / AddRows not rendering any result on map despite array of values is created.
Controller Code (chart creation code)
$countryIso = ['US','CA','BR'];
foreach ($countryIso as $isocode) {
$productDDP[$isocode] = $this->product->priceCalc($product = $product, $countryIso = $isocode);
}
View Results: using different variants of Code and giving errors:
If I print the result of print_r($productDDP);
it displays the following code:
Array
(
[US] => 900
[CA] => 1,276
[BR] => 1,215
)
I tried different approaches:
with ->addRows(array($productDDP));
"Invalid number of cells, must be less than or equal to the number of columns."
with ->addRow(array($productDDP)); or using ->addRow([$productDDP]);
Argument 3 passed to Khill\Lavacharts\DataTables\Cells\Cell::__construct() must be of the type array, string given
with ->addRows($productDDP);
Argument 1 passed to Khill\Lavacharts\DataTables\DataTable::addRow() must be of the type array or null, string given
with ->addRow(array([$productDDP]))
Render the chart but no value is set on the map.
Questions?
- What I have to use for that kind of arrays?
- addRow or addRows?.
- In which format do we have to pass array data for addRow/s?
Taking into consideration I passed all possible variants to addrow() I don't know if its an issue or a coding problem.
any help appreciated.
the array is in the wrong format
first, you're creating a single array, with key / value pairs
Array
(
[US] => 900
[CA] => 1,276
[BR] => 1,215
)
each row should be an array with two values, no key value pairs
something like...
Array
(
[0] => Array
(
[0] => US
[1] => 900
)
[1] => Array
(
[0] => CA
[1] => 1276
)
[2] => Array
(
[0] => BR
[1] => 1215
)
)
try building the arrays like this...
$countryIso = ['US','CA','BR'];
$productDDP = [];
foreach ($countryIso as $isocode) {
$productDDP[] = array($isocode, $this->product->priceCalc($product = $product, $countryIso = $isocode));
}
then use addRows
addRows($productDDP);
I have 2 input arrays, one for ingredients and one for the amount of the ingredient that is required for an associated recipe. My pivot table has four columns - id, recipe_id, ingredient_id and amount. I want to use the sync method to update the pivot table, however I can't work out how I would go about passing the second 'amounts' array values and ensuring they are synced with the correct record?
$ingredients = $request->ingredients;
$ingredientAmounts = $request->ingredients_amount;
$project->ingredients()->sync( $ingredients => ['amount' => $ingredientAmounts] );
The ingredient and its amount will both have the same key so I guess I could loop through them manually and update the pivot table, but I feel like there will be a simpler way which will make better use of eloquent.
The two input arrays need to be merged to be in the format required:
$user->roles()->sync([1 => ['expires' => true], 2, 3]);
From https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships
$array = [];
foreach ($ingredients as $key => $ingredient) {
$array[$ingredient->id] = ['amount' => $ingredientAmounts[$key]];
}
$project->ingredients()->sync($array);
I have table call users , like
id name amount created
1 a 100 6-16-2016
2 b 200 5-16-2016
I need max amount full row, I have tried below code but getting syntax error.
$user = $this->Users->find('all',[
'fields' => array('MAX(Users.amount) AS amount'),
]);
simplest way
$user = $this->Users->find('all',[
'fields' => array('amount' => 'MAX(Users.id)'),
]);
using select instead of an options array
$user = $this->Users->find()
->select(['amount' => 'MAX(Users.id)']);
making use of cake SQL functions
$query = $this->Users->find();
$user = $query
->select(['amount' => $query->func()->max('Users.id')]);
the above three all give the same results
if you want to have a single record you have to call ->first() on the query object:
$user = $user->first();
$amount = $user->amount;
Simplest method using CakePHP 3:
$this->Model->find('all')->select('amount')->hydrate(false)->max('amount')
Will result in an array containing the maximum amount in that table column.
Is is better to disable hydration before getting the results, to get the results as an array, instead of entity. Below is a complete example of how to get the results in an array, with distinct steps:
//create query
$query = $this->Users->find('all',[
'fields' => array('amount' => 'MAX(Users.id)'),
]);
$query->enableHydration(false); // Results as arrays instead of entities
$results = $query->all(); // Get ResultSet that contains array data.
$maxAmount = $results->toList(); // Once we have a result set we can get all the rows
I have an array of elements in the form of:
Array ( [0] => 16 [1] => 14 [2] => 1 [3] => 13 )
Now I need to extract only rows which ID is not one of the values in the array. Right now I'm using the following code:
$items = ArrayHelper::map(User::find()->where(['<>', 'id', $array])->all(), 'id', 'name');
Unfortunately this compares the ids in the database with just the first element of an array.
Suggestions?
Try to use not in instead of <>
You can try following code example,
$arr = [16,14,1,13];
$items = ArrayHelper::map(User::find()->where(['id'=>$arr])->all(), 'id', 'name');
It works for me.
I tyed get with the method $this>model->find() an array with ids of my model that have this form:
Array ( [0] => 2, [1] => 3) (value are the IDs)
and I try $this->model->find('list') I thought that would work too but for some strange reason I have done:
$this->model->find('list',array('recursive' => -1 ,'fields' => array('model.type_id'),'conditions'=>$cond));
and the query result is:
SELECT `model`.`round_id`, `model`.`type_id` FROM `database`.`model` AS `X` WHERE `X`.`Round_id` = '1'
If I make this query to the database returns two values but cakephp returns only one:
Array ( [1] => 2 )
i do not know that may be going
I would use
$ids = $this->Model->find('list', array('fields' => array('id')));
if you really need the 0 based integer keys, you can still do:
$ids = array_values($ids);
but that is not necessary IMO.
Update:
After your question update the whole meaning of your question itself changed:
If you specify only id, they keys and values will both be filled with it.
Using 'fields' => array('round_id', 'type_id') you have round_id filling the keys, and type_id filling the values for find(list).
find(list) returns always a list (key + value row). If you don't want that use find(all) then.