I have a stupid little question.
As I already know a select query in Laravel will always return an array of results,
I have this query:
$id = DB::select(
'select id from users where username = ?', array(Session::get('theuser')));
by inserting this id into my table
DB::table('characters')->insert(array(
'id' => $id,
'char_name' => $charname,
'char_dynasty' => $dynastyname,
'picture' => 'Male1.png'
));
I will get the error: ksort() expects parameter 1 to be array, string given.
How can I get rid of this? Thanks in advance!
At least one of $id, $charname or $dynastyname is an array and should not be.
You are using it wrong.
Below is a POC proving this.
The output is "Warning: ksort() expects parameter 1 to be array, integer given on line 13"
It runs as expected when providing 'id' => 'a'.
function insert(array $values)
{
if ( ! is_array(reset($values)))
{
$values = array($values);
}
else
{
foreach ($values as $key => $value)
{
ksort($value); $values[$key] = $value;
}
}
var_dump($values);
}
insert(array(
'id' => array('a'),
'char_name' => 2,
'char_dynasty' => 3,
'picture' => 'Male1.png'
));
Related
I use laravel 5.6
I have a json file containing 500 thousand records. I want to create a logic to check whether the id of each record already exists or not in the database. If it doesn't already exist, then there will be a data insert process. If it already exists, there will be a data update process. Before updating the data, it will check whether last_modified_date in json file and database is the same or different. If it's different then it will update
I have made logic. I just want to make sure whether my logic is effective or not
My logic code like this :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
$last_modified_date = \Carbon\Carbon::parse($value['Last_Modified_Date']);
$data = \DB::table('details')->where('id', '=', $value['Code'])->get();
if ($data->isEmpty()) {
\DB::table('details')->insert(
[
'id' => $value['Code'],
'number' => $value['Number'],
'last_modified_at' => $last_modified_date,
...
]
);
}
else {
\DB::table('details')
->where('id', '=', $value['Code'])
->where('last_modified_at', '<>', $last_modified_date)
->update([
'id' => $value['Code'],
'number' => $value['Number'],
'last_modified_at' => $last_modified_date,
...
]);
}
}
The code is working. But the process seems really long
Do you have another solution that is better?
Update
I find another solution use updateOrCreate
I try like this :
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
Details::updateOrCreate(
[ 'id' => $value['Code'] ],
[ 'number' => $value['Number'], 'last_modified_at' => $last_modified_date, ... ]
);
}
What do you think?
you can not use <> in updateOrCreate
i hope this code could help you:
$path = storage_path('data.json');
$json = json_decode(file_get_contents($path), true);
foreach ($json['value'] as $value) {
$detail = Details::firstOrCreate(
[ 'id' => $value['Code'] ],
[ 'number' => $value['Number'], 'last_modified_at' => $last_modified_date, ... ]
);
if($detail->last_modified_at != $last_modified_date) {
$detail->update([
'number' => $value['Number'],
'last_modified_at' => $last_modified_date,
...
]);
}
}
Tearing my hair out at this point, hopefully someone can help me out!
I am using the Kartik-V Typeahead Advanced widget with Yii2.
The plugin works, in that the functionality is working perfectly on the page, I search and the results appear in the auto complete list.
Unfortunately, I am unable to store the result in my database. I am seeing an issue on the following line:
->where([ 'name' => $model->name ])//This variable is returning null
Am I trying to store the data incorrectly? I have tried everything I can think of, but I am sure someone here will come up with something better!
See below for the full code.
My controller:
public function actionIndex()
{
$model = new Member();
if ($model->load(Yii::$app->request->post())) {
$test = Test::find()
->where([ 'name' => $model->name ])//This variable is returning null
->one();
$test->updateCounters(['times_used' => 1]);
}
return $this->render('index', [
'model' => $model,
]);
}
/*************
* Initial prefetch of results
*************/
public function actionPrefetchlist() {
$query = new Query;
$query->select('name')
->from('test_table')
->limit(10)
->orderBy('times_used');
$command = $query->createCommand();
$data = $command->queryAll();
$out = [];
foreach ($data as $d) {
$out[] = ['value' => $d['name']];
}
echo Json::encode($out);
}
/*************
* Remote results
*************/
public function actionRemotelist() {
$query = new Query;
$query->select('name')
->from('test_table')
->where('name LIKE "%' . $q .'%"')
->limit(10)
->orderBy('times_used');
$command = $query->createCommand();
$data = $command->queryAll();
$out = [];
foreach ($data as $d) {
$out[] = ['value' => $d['name']];
}
echo Json::encode($out);
}
The view file:
echo $form->field($model, 'name')->label(false)->widget(Typeahead::classname(), [
'name' => 'name',
'options' => ['placeholder' => 'Filter as you type ...'],
'pluginOptions' => ['highlight'=>true],
'dataset' => [
[
'datumTokenizer' => "Bloodhound.tokenizers.obj.whitespace('value')",
'display' => 'value',
'prefetch' => Url::to(['prefetchlist']),
'remote' => [
'url' => Url::to(['remotelist']) . '?q=%QUERY',
'wildcard' => '%QUERY'
]
]
]
]);
you ask here for a new model:
$model = new Member();
so you get a empty model
so the $model->name is empty
if you set the model $model->name='test';
than it will be filled so, fill the model first
So it turns out it was a massive rookie error.
If anyone else stumbles upon something similar, I removed the attribute name from the model's "rules()"
I need an integer in the database but I wanted users to enter in a string (I would then convert it in the controller). Removing it from the rule broke everything.
Hopefully this helps someone else :)
I'm new to cakephp2 and mysql and need some help.
I want to get the data from yesterday and daybefore yesterday date from the same Model in cakephp2,
However the conditions will be different so I am trying to get the data by making two different methods that contains the find() with different conditions. ,however,I'ts not working. Here is the sample below ↓
This method getYesterday() will return the data as a array but I want to add a condition
that will check if the pageview count is not 0, how will I do that ?
public function getYesterday() {
$yes = array();
$dt = date('Y-m-d', strtotime('-1 day'));
// $dy = date('Y-m-d', strtotime('-2 day'));
$yesterday = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as yesterday_pv'),
'conditions' => array('dt' => "2014/09/26", 'is_crawler' => 0,'count(page_view)>'=>0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($yesterday as $y) {
$yes[] = $y;
//$i++;
}
return $yes;
}
The function below will get the data from daybefore yesterday
public function getDBY() {
$dayyes = array();
$dt = date('Y-m-d', strtotime('-2 day'));
$daybefore = $this->PvLog->find('all', array(
'fields' => array('dt', 'params', 'count(params) as daybefore_pv'),
'conditions' => array('dt' => "{$dt}", 'is_crawler' => 0),
'group' => array('params'),
'order' => array('count(params)' => 'DESC'),
));
foreach ($daybefore as $dby) {
$dayyes[] = $dby;
//$i++;
}
return $dayyes;
}
The probelem is I'm not sure about this way, Is there a better solution that you can get the different result with different conditions in mysql cakephp2 ? The main thing I want to do Is to get the yesterdays data and daybefore yesterdays data from the same model but I'm not sure how I can do this, I've checked cakes documents but cant find the solution. Sorry for my broken English.
hi guys i'm making an api in laravel 4 !! so im getting data that i store and return a json response everyting is good but just one thing :)
this is part of th code that return a response
if( $user->save() )
{
$id = DB::table('users')
->where('pseudo','LIKE',$pseudo)
->select('id')
->get();
return Response::json(array(
'status' => 'ok',
'message' => 'success',
'userId' => $id
));
}
the reponse is
{"status":"ok","message":"success","userId":[{"id":11}]}
but i whant to get this response
{"status":"ok","message":"success","userId":11}
how can i do it im trying but nothing chaged ! thx
You are setting 'userId' equal to the entire $id object returned from the query. You really just want
return Response::json(array(
'status' => 'ok',
'message' => 'success',
'userId' => $id['id']
));
Just something a little bit neater:
$id = DB::table('users')
->where('pseudo','LIKE',$pseudo)
->pluck('id'); // Retrieve first result, column 'id'
I want all nodes of each key sorted by key in hash ref or array or something like so that I can iterate that according to my need since I have to display each key with its all children.
following is my data structure:
$hash1 = {
'3' => {
'title' => 'Parent-3',
'parentid' => '-1'
},
'1' => {
'children' => {
'11' => {
'title' => 'child-1',
},
'5' => {
'children' => {
'8' => {
'title' => 'first child of child-2',
},
'13' => {
'title' => 'second child of child-2',
}
},
'title' => 'child-2',
}
},
'title' => 'Parent-1',
'parentid' => '-1'
},
'2' => {
'title' => 'Parent-2',
'parentid' => '-1'
},
'4' => {
'title' => 'Parent-4',
'parentid' => '-1'
},
};
I have used following functions :
sub Options {
my $hash = shift;
my $options = '';
my $iter; $iter = sub {
my $hash = shift;
my $indent = shift || '';
foreach my $k (sort {$a <=> $b} keys %{$hash}) {
my $v = $hash->{$k};
if($v->{parentid} eq '-1'){
$options .= $v->{title} ."-parent\n";
}else{
$options .= $v->{title} . "," ;
}
if ($v->{children}){
$iter->($v->{children}, $indent . "");
}
}
chop($options);
$options .= "\n";
};
$iter->($hash);
return $options;
}
here it returns a string with comma separated but I need some kind of data structure so that I can able to find all children for each key (in the form of hash ref or array) like:
Parent-1 -> [child-1,child-2, first child of child-2, second child of child-2]
Parent-2
Parent-3
Parent-4
any one can help me out? thanks in advance.
If your only goal is to display the hash contents, you should use the Data::Dumper module. It can be used to print data structures of arbitrary complexity with a good format.
You may also find brian d foy's answer on checking key existence useful
The code for with code for walking a data structure and Data::Diver may give you all the help you need.