Error:You must specify an orderBy clause when using this function - laravel

I am getting the following error while trying to migrate. Actually, I have a lot of data so I used the chunk in laravel.
I am using MongoDB not SQL
** You must specify an orderBy clause when using this function.**
My migration file's up function is is
public function up()
{
ini_set('max_execution_time', 250);
ini_set('memory_limit', '1024M');
$product_array = DB::collection('product')->orderBy('created_at','asc');
$product_array->chunk(20, function($product_array)
{
$cotationPercentForecast=0;
$cotationPercent=0;
$quote_tpl = array();
foreach ($product_array as $key => $value) {
if (isset($value['quote_tpl'])) {
$quote_tpl = $value['quote_tpl'];
$defaultScoreCount = 0;
$realScoreCount = 0;
$forecastScoreCount = 0;
foreach ($quote_tpl as $idxPerimetre => $perimetre) {
if (isset($perimetre['families'])) {
foreach ($perimetre['families'] as $idxFamilies => $family) {
if (isset($family['subfamilies'])) {
foreach ($family['subfamilies'] as $idxSubFamilies => $subfamily) {
if (isset($subfamily['items'])) {
foreach ($subfamily['items'] as $idxitem => $item) {
if (isset($item['criterias'])) {
foreach ($item['criterias'] as $idxcriteria => $criteria) {
if (!isset($criteria['inactive']) || $criteria['inactive'] != 'true') {
$defaultScoreCount++;
if (isset($criteria['real_score'])) {
$realScoreCount++;
}
if (isset($criteria['forecast_score'])) {
$forecastScoreCount++;
}
}
} // FOREACH CRITERIA
} // ISSET CRITERIA ###
} // FOREACH ITEM
} // ISSET ITEM ###
} // FOREACH SUBFAMILY
} // ISSET SUBFAMILY ###
} // FOREACH FAMILY
} // ISSET FAMILY ###
}// FOREACH PERIMETER ##
if ($realScoreCount > 0 && $defaultScoreCount > 0) {
$cotationPercentUn = ($realScoreCount / $defaultScoreCount) * 100;
$cotationPercent = round($cotationPercentUn, 2);
}
if ($forecastScoreCount > 0 && $defaultScoreCount > 0) {
$cotationPercentUnForecast = ($forecastScoreCount / $defaultScoreCount) * 100;
$cotationPercentForecast = round($cotationPercentUnForecast, 2);
}
$results = DB::collection('product')->update(['cotation_percent' => $cotationPercent,'forecast_cotation_percent' => $cotationPercentForecast]);
}
}
});
}
I have gone through many answers here and almost all suggest to use orderBy so I used it. But still getting the error.
i have used
Product::chunk(5, function($product_array){}
Any help is appreciated. Thanks in advance.

This warning is added when Laravel internally uses enforceOrderBy which is defined inside Illuminate/Database/Query/Builder.
Whenever you use chunk on a query builder instantiated by DB facade Illuminate\Database\Query\Builder directly, it would ask you :
You must specify an orderBy clause when using this function.
So it will happen if you are doing :
\DB::table('product')->chunk(10, function($product){
...
});
If you manually add an order by to this, it will not throw the error and will work as expected :
\DB::table('product')->orderBy('created_at')->chunk(10, function($product){
...
});
However, its better to use the Eloquent Model directly like which will not enforce you to add an order by clause manually :
Product::chunk(10, function($product){
...
});
Also there is no method DB::collection(), you can use DB::table() instead if you wish, unless you are using mongodb and not MySQL

Related

Display large array in laravel blade in too much time

so i got imported my large excel file with huge informations with 1 sec and i did get all the information i need to display within 1 sec to , but i got a big probleme when displaying the array in the view coz i m testing if the cells are correct or not i m using 5 ifs and 3 foreach and it takes mote than 2 mins , i need help to display all the info in a short time this is my array , and thanks
and there is my code of the view which takes to much time to display infos
and thanks
//here we get our final result of true and false fields
$finale_array = [];
// here we get all our
$current_table2 = [];
$results_applied = [];
$current_result = [];
$columns = SCHEMA::getColumnListing('imports');
// here we get all our conditions
$conditions = DB::table('conditions')->select('number', 'field', 'value')->get();
// here we get all our data
$imports = DB::table('imports')->get();
$results = DB::table('results')->get();
$x = 0;
$default_value = 0;
foreach ($imports as $key => $imported) {
$res = get_object_vars($imported);
foreach ($conditions as $value) {
$array = get_object_vars($value);
$result = $this->test($columns, $array['field']); // the result of our test function
if ($result == "ok") {
if ($res[$array['field']] == $array['value']) {
foreach ($results as $value_result) {
$res_resultat = get_object_vars($value_result);
$test_field = $this->test($columns, $res_resultat['field']);
// testing if the condtion numder match with the result number
if (($res_resultat['condition_number'] == $array['number'])) {
if (($test_field == 'ok')) {
if ($res['id'] != $default_value) {
// here test if the difference between the id and the default value is different from the current id to insert
if (($res['id'] - $default_value) != $res['id']) {
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
$current_table2 = [];
$results_applied = [];
$default_value = $res['id'];
}
$current_table2 = [$res, $res['id']];
}
$current_result = [$res_resultat['field'], $res[$res_resultat['field']]];
if ($res_resultat['value'] == $res[$res_resultat['field']]) {
$current_result[2] = 'true';
$current_result[3] = $res_resultat['value'];
} else {
$current_result[2] = 'false';
$current_result[3] = $res_resultat['value'];
}
$current_result[4] = $array['number'];
array_push($results_applied, $current_result);
}
}
}
}
}
}
$default_value = $res['id'];
}
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
dd($finale_array);
return view('Appliedconditions', ['imports' => $finale_array, 'columns' => $columns]);
}
From what I can see, you are recovering all the data without paging it.
You must paginate the data using the paginate(#elements_per_page) directive in your query, where #elements_per_page is the number of elements you want to display per page.
For example:
$elements = Elements::select('*')->paginate(10);
and in your blade view you can retreive pagination links after the closing table tag in this way: {{ $elements->links() }}

Phalcon use Oracle views

In a Phalcon project, I have multiple database in Oracle and mySQL with number of tables and views. Created models for corresponding tables and views. But unable to access views. I initialize in model below:
public function initialize()
{
$this->setConnectionService('dbBznes');
$this->setSchema('POLICY');
$this->setSource("BUSINESS_ALL");
}
As per the comments, this is apparently a metadata issue and the default metadata strategy is introspection and is attempting to check if the table exists. You can set up your own metadata strategy like so:
$di['modelsMetadata'] = function()
{
$metadata = new \Phalcon\Mvc\Model\MetaData\Memory();
$metadata->setStrategy(
new MyIntrospectionStrategy()
);
return $metadata;
};
"Memory" in this case means don't use any sort of metadata caching. This goes off into another tangent as you can cache in many ways for more speed in production, etc.
As for the MyIntrospectionStrategy class above, it represents your own class based on Phalcon's Introspection strategy which attempts to analyze the database to figure out the fields and their types involved with the table.
I believe I converted Phalcon\Mvc\Model\MetaData\Strategy\Introspection from Zephir to PHP correctly as follows:
class MyIntrospectionStrategy implements \Phalcon\Mvc\Model\MetaData\StrategyInterface
{
public final function getMetaData(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector)
{
$schema = $model->getSchema();
$table = $model->getSource();
$readConnection = $model->getReadConnection();
if( !$readConnection->tableExists($table, $schema) )
{
if($schema)
{
$completeTable = $schema . "'.'" . $table;
} else {
$completeTable = $table;
}
throw new \Phalcon\Mvc\Model\Exception(
"Table '" . $completeTable . "' doesn't exist in database when dumping meta-data for " . get_class($model)
);
}
$columns = $readConnection->describeColumns($table, $schema);
if( !count($columns) )
{
if($schema)
{
$completeTable = $schema . "'.'" . $table;
} else {
$completeTable = $table;
}
/**
* The table not exists
*/
throw new \Phalcon\Mvc\Model\Exception(
"Cannot obtain table columns for the mapped source '" . completeTable . "' used in model " . get_class(model)
);
}
$attributes = [];
$primaryKeys = [];
$nonPrimaryKeys = [];
$numericTyped = [];
$notNull = [];
$fieldTypes = [];
$fieldBindTypes = [];
$automaticDefault = [];
$identityField = false;
$defaultValues = [];
$emptyStringValues = [];
foreach($columns as $column)
{
$fieldName = $column->getName();
$attributes[] = $fieldName;
if ($column->isPrimary() === true)
{
$primaryKeys[] = $fieldName;
} else {
$nonPrimaryKeys[] = $fieldName;
}
if ($column->isNumeric() === true)
{
$numericTyped[$fieldName] = true;
}
if ($column->isNotNull() === true)
{
$notNull[] = $fieldName;
}
if ($column->isAutoIncrement() === true)
{
$identityField = $fieldName;
}
$fieldTypes[$fieldName] = $column->getType();
$fieldBindTypes[$fieldName] = $column->getBindType();
$defaultValue = $column->getDefault();
if ($defaultValue !== null || $column->isNotNull() === false)
{
if ( !$column->isAutoIncrement() )
{
$defaultValues[$fieldName] = $defaultValue;
}
}
}
return [
\Phalcon\Mvc\Model\MetaData::MODELS_ATTRIBUTES => $attributes,
\Phalcon\Mvc\Model\MetaData::MODELS_PRIMARY_KEY => $primaryKeys,
\Phalcon\Mvc\Model\MetaData::MODELS_NON_PRIMARY_KEY => $nonPrimaryKeys,
\Phalcon\Mvc\Model\MetaData::MODELS_NOT_NULL => $notNull,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES => $fieldTypes,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES_NUMERIC => $numericTyped,
\Phalcon\Mvc\Model\MetaData::MODELS_IDENTITY_COLUMN => $identityField,
\Phalcon\Mvc\Model\MetaData::MODELS_DATA_TYPES_BIND => $fieldBindTypes,
\Phalcon\Mvc\Model\MetaData::MODELS_AUTOMATIC_DEFAULT_INSERT => $automaticDefault,
\Phalcon\Mvc\Model\MetaData::MODELS_AUTOMATIC_DEFAULT_UPDATE => $automaticDefault,
\Phalcon\Mvc\Model\MetaData::MODELS_DEFAULT_VALUES => $defaultValues,
\Phalcon\Mvc\Model\MetaData::MODELS_EMPTY_STRING_VALUES => $emptyStringValues
];
}
public final function getColumnMaps(\Phalcon\Mvc\ModelInterface $model, \Phalcon\DiInterface $dependencyInjector)
{
$orderedColumnMap = null;
$reversedColumnMap = null;
if (method_exists($model, 'columnMap'))
{
$userColumnMap = $model->columnMap();
if ( gettype($userColumnMap) != 'array')
{
// Bad grammer directly in cphalcon :sadface:
throw new \Phalcon\Mvc\Model\Exception('columnMap() not returned an array');
}
$reversedColumnMap = [];
$orderedColumnMap = $userColumnMap;
foreach($userColumnMap as $name => $userName)
{
$reversedColumnMap[$userName] = $name;
}
}
return [$orderedColumnMap, $reversedColumnMap];
}
}
I have not tested this.
As far as adding support for views to be treated like tables, the change might be as simple as:
Before:
if( !$readConnection->tableExists($table, $schema) )
After:
if( !$readConnection->tableExists($table, $schema) && !$readConnection->viewExists($table, $schema) )
If this doesn't work due to logic choking with describeColumns, you might need to write something specific for working with views in Oracle for this dialect.
As far as other solutions, you can provide your own metadata method directly on the model by specifying your ownmetaData method directly on it.
Another solution is to use annotations instead of introspection for metadata.
Then you'd place your metadata as comments in the code for Phalcon to parse.
If you continue to run into problems with Database Views, just run it as raw SQL rather than attempting to use the ORM to do it. You can simply define a new method on your model to run the raw SQL.

Laravel 5.3 database transaction issue?

I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}
Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}

Modify the MY_Router.php file for QUERY STRING Codeigniter 3.0.6

I use codeigniter 3.0.6 query string like
index.php?d=directoryt&c=controller
index.php?d=directory&c=controller&m=function
How ever having two get methods for directory and controller is a bit long.
Question Is there any way to modify the protected function
_set_routing() function using a MY_Router.php to get it so it will pick up the directory and controller by using one query only like example below.
index.php?route=directory/controller
// If need to get function
index.php?route=directory/controller&m=function
What have tried so far
<?php
class MY_Router extends CI_Router {
protected function _set_routing()
{
// Load the routes.php file. It would be great if we could
// skip this for enable_query_strings = TRUE, but then
// default_controller would be empty ...
if (file_exists(APPPATH.'config/routes.php'))
{
include(APPPATH.'config/routes.php');
}
if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/routes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/routes.php');
}
// Validate & get reserved routes
if (isset($route) && is_array($route))
{
isset($route['default_controller']) && $this->default_controller = $route['default_controller'];
isset($route['translate_uri_dashes']) && $this->translate_uri_dashes = $route['translate_uri_dashes'];
unset($route['default_controller'], $route['translate_uri_dashes']);
$this->routes = $route;
}
// Are query strings enabled in the config file? Normally CI doesn't utilize query strings
// since URI segments are more search-engine friendly, but they can optionally be used.
// If this feature is enabled, we will gather the directory/class/method a little differently
if ($this->enable_query_strings)
{
// If the directory is set at this time, it means an override exists, so skip the checks
if ( ! isset($this->directory))
{
$_route = isset($_GET['route']) ? trim($_GET['route'], " \t\n\r\0\x0B/") : '';
if ($_route !== '')
{
echo $_route;
$this->uri->filter_uri($_route);
$this->set_directory($_route);
}
}
// Routing rules don't apply to query strings and we don't need to detect
// directories, so we're done here
return;
}
// Is there anything to parse?
if ($this->uri->uri_string !== '')
{
$this->_parse_routes();
}
else
{
$this->_set_default_controller();
}
}
}
config.php
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = TRUE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
// Modifyed in MY_Router.php
$config['route'] = 'route';
I have it working
<?php
class MY_Router extends CI_Router {
protected function _set_routing() {
if (file_exists(APPPATH.'config/routes.php'))
{
include(APPPATH.'config/routes.php');
}
if (file_exists(APPPATH.'config/'.ENVIRONMENT.'/routes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/routes.php');
}
// Validate & get reserved routes
if (isset($route) && is_array($route))
{
isset($route['default_controller']) && $this->default_controller = $route['default_controller'];
isset($route['translate_uri_dashes']) && $this->translate_uri_dashes = $route['translate_uri_dashes'];
unset($route['default_controller'], $route['translate_uri_dashes']);
$this->routes = $route;
}
if ($this->enable_query_strings) {
if ( ! isset($this->directory))
{
$route = isset($_GET['route']) ? trim($_GET['route'], " \t\n\r\0\x0B/") : '';
if ($route !== '')
{
$part = explode('/', $route);
$this->uri->filter_uri($part[0]);
$this->set_directory($part[0]);
if ( ! empty($part[1])) {
$this->uri->filter_uri($part[1]);
$this->set_class($part[1]);
// Testing function atm
if ( ! empty($_GET['function']))
{
$this->uri->filter_uri($_GET['function']);
$this->set_method($_GET['function']);
}
$this->uri->rsegments = array(
1 => $this->class,
2 => $this->method
);
}
} else {
$this->_set_default_controller();
}
}
// Routing rules don't apply to query strings and we don't need to detect
// directories, so we're done here
return;
}
// Is there anything to parse?
if ($this->uri->uri_string !== '')
{
$this->_parse_routes();
}
else
{
$this->_set_default_controller();
}
}
}

Filtering Eloquent Collection

Trying to filter a collection object down based upon any combination of multiple values. This is as far as I've got. Not happening. Any clues for me?
public function search()
{
$posts = Posting::all();
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($country_id) && $country_id>0 )
{
return $post->where('country_id','=',$country_id);
}
})->values();
$posts = $posts->filter(function($post)
{
if( !empty($province_id) && $province_id>0 )
{
return $post->where('province_id','=',$province_id);
}
})->values();
return $posts;
}
Any help appreciated.
First off, you should really do a validation for the id being larger than 0, if they were provided. You shouldn't be manually checking that out.
But anyhow, why are you using filter, when you can just directly use Eloquent (I omitted the check for id being bigger than 0):
$type_id = Input::get('type_id');
$country_id = Input::get('country_id');
$province_id = Input::get('province_id');
$query = Posting::query();
if ( ! empty($type_id)) $query->whereTypeId($type_id);
if ( ! empty($country_id)) $query->whereCountryId($country_id);
if ( ! empty($province_id)) $query->whereProvinceId($province_id);
return $query->get();
First off, you need to return something that makes sense from the closure in your filter:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->where('type_id','=',$type_id);
}
})
Above returns Eloquent\Builder object, which is evaluated to true, so.. it really doesn't make sense.
This is what you need:
$posts = $posts->filter(function($post)
{
if( !empty($type_id) && $type_id>0 )
{
return $post->type_id == $type_id; // bool
}
})
With such code, you will filter the collection. $posts now will hold only those items, that match the statement in that closure.

Resources