Can't figure out a query to upsert collection into a tablr - mysql

I want to insert or update rows into my models table. But can't figure out the query.
SmStudentAttendance This is my model.
$students is my collection.
I have put the collection fields in arrays.
foreach ($students as $student) {
array_push($temp_id, $student->id);
array_push($temp_lastname, $student->last_name);
array_push($temp_academic_id, $student->academic_id);
array_push($temp_attendance, 'P');
array_push($temp_attendancedate, $date);
array_push($temp_schoolid, '1');
array_push($temp_updatedby, '1');
array_push($temp_createdby, '1');
}
Now I want to insert them if a row for the student_id and attendance_date is not present in the table else update if it already exists.
This is the query:
SmStudentAttendance::upsert('attendance_type', $temp_attendance, 'attendance_date', $temp_attendancedate, 'student_id', $temp_id, 'created_by', $temp_createdby, 'updated_by', $temp_updatedby, 'school_id', $temp_schoolid, 'academic_id', $temp_academic_id);
Error I am geting:
Argument 1 passed to Illuminate\Database\Eloquent\Builder::upsert() must be of the type array, string given, called in D:\xampp\htdocs\sms\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 23

You're creating your arrays for columns rather than rows, this will cause problems, consider this code instead:
$studentRows = [];
foreach ($students as $student) {
$studentRows[] = [
'id' => $student->id,
'last_name' => $student->last_name,
'academic_id' => $student->academic_id,
'attendance_type' => 'P',
'attendance_date' => $date,
// .... rest of the fields
]
}
SmStudentAttendance::upsert($studentRows, [ 'id', 'last_name', 'academic_id' ], [ 'attendance_type', 'attendance_date' ]);
In general the idea is you pass it an array of rows you want to upsert, then an array of fields to match and an array of fields to update. Then Laravel will make queries find all rows that match the fields specified and update those and then insert the rows that did not match the given fields.

The error message, "Argument 1 passed to Illuminate\Database\Eloquent\Builder::upsert() must be of the type array, string given", suggests that the first parameter needs to be an array rather than the string you are setting.
Take a look at the documentation for this at https://laravel.com/docs/8.x/eloquent#upserts for an example. The method accepts two arrays. The first contains all of the data to be updated, the second the fields which uniquely identify the record. You will need to update your method call to match this syntax.

Related

Multiple Fields with a GroupBy Statement in Laravel

Already received a great answer at this post
Laravel Query using GroupBy with distinct traits
But how can I modify it to include more than just one field. The example uses pluck which can only grab one field.
I have tried to do something like this to add multiple fields to the view as such...
$hats = $hatData->groupBy('style')
->map(function ($item){
return ['colors' => $item->color, 'price' => $item->price,'itemNumber'=>$item->itemNumber];
});
In my initial query for "hatData" I can see the fields are all there but yet I get an error saying that 'colors', (etc.) is not available on this collection instance. I can see the collection looks different than what is obtained from pluck, so it looks like when I need more fields and cant use pluck I have to format the map differently but cant see how. Can anyone explain how I can request multiple fields as well as output them on the view rather than just one field as in the original question? Thanks!
When you use groupBy() of Laravel Illuminate\Support\Collection it gives you a deeper nested arrays/objects, so that you need to do more than one map on the result in order to unveil the real models (or arrays).
I will demo this with an example of a nested collection:
$collect = collect([
collect([
'name' => 'abc',
'age' => 1
]),collect([
'name' => 'cde',
'age' => 5
]),collect([
'name' => 'abcde',
'age' => 2
]),collect([
'name' => 'cde',
'age' => 7
]),
]);
$group = $collect->groupBy('name')->values();
$result = $group->map(function($items, $key){
// here we have uncovered the first level of the group
// $key is the group names which is the key to each group
return $items->map(function ($item){
//This second level opens EACH group (or array) in my case:
return $item['age'];
});
});
The summary is that, you need another loop map(), each() over the main grouped collection.

Laravel updateOrCreate with auto-incremental database

My purpose is to update if the value exists, else inserts a new row in the database table after submitting the form.
The problem is, the function here adds new columns in db table instead of updating them.
Here's my function :
MyModel::updateOrCreate(array(
'myField' => 'myValue',
))
->where('myAutoIncrementalField', '=', '5')
->where('myPrimaryKey', '=', '8');
My database table is like that :
1. myPrimaryKey (not auto incremental and is fillable on model.)
2. myAutoIncrementalField (auto incremental and cannot be fillable on model.)
Thank you in advance.
This is how you use this method:
Model::updateOrCreate(
['primary_key' => 8],
['field' => 'value', 'another_field' => 'another value']
);
As 1st param pass an array of fields that are unique, or in your case, the primary key. Non-unique fields don't make sense here obviously just like passing anything along with the PK.
2nd param is an array of values that should be updated/created too, but being ignored in the unique/pk search.
You cannot use where functions with this method. You have to include the where clauses in the array.
MyModel::updateOrCreate(array(
'myField' => 'myValue',
'myAutoIncrementalField' => '5',
'myPrimaryKey' => '8'
));

How to add combined unique fields validator rule in Laravel 4

I am using Laravel 4.2 and mysql db . I have an exam table in which i am taking Exams entry and the fields are --> id | examdate | batch | chapter | totalmarks
I have made a combined unique key using $table->unique( array('examdate','batch','chapter') ); in schema builder.Now I want to add a validation rule to it. I know i can add unique validation by laravel unique validator rule but the problem is ,it checks only for one field . I want it to add uniqueness to the 3 fields combined(user must not be able to add second row with same value combination of examdate,batch and chapter fields).
Is it even possible to do it in laravel 4 .Is there any workaround if its not possible?
You could write a custom validator rule. The rule could look something like this:
'unique_multiple:table,field1,field2,field3,...,fieldN'
The code for that would look something like this:
Validator::extend('unique_multiple', function ($attribute, $value, $parameters)
{
// Get table name from first parameter
$table = array_shift($parameters);
// Build the query
$query = DB::table($table);
// Add the field conditions
foreach ($parameters as $i => $field)
$query->where($field, $value[$i]);
// Validation result will be false if any rows match the combination
return ($query->count() == 0);
});
You can use as many fields as you like for the condition, just make sure the value passed is an array containing the values of the fields in the same order as declared in the validation rule. So your validator code would look something like this:
$validator = Validator::make(
// Validator data goes here
array(
'unique_fields' => array('examdate_value', 'batch_value', 'chapter_value')
),
// Validator rules go here
array(
'unique_fields' => 'unique_multiple:exams,examdate,batch,chapter'
)
);
It didn't work for me so I adjusted the code a tiny bit.
Validator::extend('unique_multiple', function ($attribute, $value, $parameters, $validator)
{
// Get the other fields
$fields = $validator->getData();
// Get table name from first parameter
$table = array_shift($parameters);
// Build the query
$query = DB::table($table);
// Add the field conditions
foreach ($parameters as $i => $field) {
$query->where($field, $fields[$field]);
}
// Validation result will be false if any rows match the combination
return ($query->count() == 0);
});
The validator looks like this. You don't need a particular order of DB table column names as stated in the other answer.
$validator = Validator::make($request->all(), [
'attributeName' => 'unique_multiple:tableName,field[1],field[2],....,field[n]'
],[
'unique_multiple' => 'This combination already exists.'
]);

Codeigniter/Mysql: Column count doesn't match value count with insert_batch()?

Alright, so i have a huge list (like 500+) of entries in an array that i need to insert into a MySQL database.
I have a loop that populates an array, like this:
$sms_to_insert[] = array(
'text' => $text,
'contact_id' => $contact_id,
'pending' => $status,
'date' => $date,
'user_id' => $this->userId,
'sent' => "1"
);
And then i send it to the database using the built insert_batch() function:
public function add_sms_for_user($id, $sms) {
//$this->db->delete('sms', array("user_id" => $id)); Irrelevant
$this->db->insert_batch('sms', $sms); // <- This!
}
The error message i get is as follows:
Column count doesn't match value count at row 1.
Now, that doesn't make sense at all. The columns are the same as the keys in the array, and the values are the keys value. So, why is it not working?
Any ideas?
user_id turned out to be null in some situations, that's what caused the error.
EDIT: If you replace insert_batch() with a loop that runs insert() on the array keys you will get more clear error messages.

Filtering an array based on database records

I have an Array if a user's Facebook friend list as follows:
[
{ 'name' => 'John Mallock', 'id' => '123123' },
{ 'name' => 'Susan Freely', 'id' => '123123123' },
...
]
I'd like to filter this list for entries that exist in the users table in my Rails app. I'm currently doing this as follows:
graph = Koala::Facebook::API.new 'access_token'
friends = graph.get_connections 'me', 'friends' # Returns the structure above
friends.select! { |f| User.exists? :facebook_id => f['id'] }
This results in a SELECT query for every friend in the list, which is noticeably inefficient.
Is there a more effective means of filtering this list based on database records?
Probably the simplest way to do this is to pass an array into a where method in ruby. If you pass in an array, it will be converted into a IN query on the database:
users = User.where(:facebook_id => friends.map{|f| f['id']})
# generates: SELECT * FROM users where users.facebook_id IN (f1, f2, etc..)
If you need to know which entries in friends correspond to users, you could then call a select on friends:
existing_facebook_ids = users.map(&:facebook_id)
friends.select! {|f| existing_facebook_ids.include?(f['id'])}
Note that the above is pretty inefficient if you have a decent amount of records in either array. You'd probably want to optimize it somewhat, or better yet, don't use the friends array and just iterate over User records if they contain the same data.
You can use a SQL IN query to select all the IDs at once.
friend_ids = friends.map{|f| f['id']}
User.scoped(:conditions => ['id IN (?)', friend_ids])