I'm trying to pull the last inserted id from a database table so that I can input it into a new database table, like so:
$mealplaninput =
MealPlanInput::create([
'meal_type' => $meal,
'suitable_for' => $suited,
'allergens' => $allerg,
'specific_allergen' => $spec,
'no_of_people' => $nop,
'start_date' => $request->date,
'no_of_days' => $nod,
'user_id' => $currentuserid,
]);
The attempt to pull the last id (but doesn't work):
$uniquemealplanid = $mealplaninput->id();
To then input into new table:
MealPlanDisplay::create([
'MealPlan_ID' => $uniquemealplanid,
'Day' => $recipeday,
]);
However I get the error:
Call to undefined method App\Models\MealPlanInput::id()
I have tried other methods too, like:
$uniquemealplanid = $this->create($mealplaninput)->id;
But the error I get is:
Method App\Http\Controllers\MealPlanInputController::create does not exist.
How can I pull the last id from MealPlanInput?
You need to create an object from the model to get ID.
$mealplaninput = new MealPlanInput;
$mealplaninput->meal_type = $meal;
$mealplaninput->suitable_for = $suited;
$mealplaninput->allergens = $allerg;
$mealplaninput->specific_allergen = $spec;
$mealplaninput->no_of_people = $nop;
$mealplaninput->start_date = $request->date;
$mealplaninput->no_of_days = $nod;
$mealplaninput->user_id = $currentuserid;
$mealplaninput->save();
$uniquemealplanid = $mealplaninput->id;
you need to try
$uniquemealplanid = $mealplaninput->id;
insted of
$uniquemealplanid = $mealplaninput->id();
Related
I am new to larvel 5.6 and trying to learn it.
I have the following code:
$gr = group::create([
'book_id' => $book_id,
]);
$owner = Book::where('id', $book_id)->pluck('user_id');
$id1 = Auth::user()->id;
$gr->users()->sync([$id1 => ['last_seen_id' => -1], $owner => ['last_seen_id' => -1]]);
in the pivot table group_user I have one extra column which is last_seen_id but I get the error :
"Illegal offset type"
so what I tried is to change the code to the following:
$gr = group::create([
'book_id' => $book_id,
]);
$owner = Book::where('id', $book_id)->pluck('user_id');
$gr->users()->sync([Auth::user()->id => ['last_seen_id' => -1], $owner => ['last_seen_id' => -1]]);
But I keep getting the same error, please kindly help me to understand what is wrong and how to solve it.
In your code, the $owner represent the object, and by you're code, it looks like you're trying to get it to be an array, both types cannot be used as an array index, which you have in your last line.
Maybe you're trying to get only one owner id, so what I'm guessing you need to get is
$owner = Book::where('id', $book_id)->first();
if(!empty($owner)) {
$owner = $owner->user_id;
} else {
throw new \Exception();
}
I have this function that doesn't batch insert to my database, I only used the batch insert function recently because back then I only used object inserts through for loops like this
$subject = ActiveCurriculum::find()
->select('scstock.*')
->joinWith('schead')
->where(['schead.TrNo' => $TrNo])
->one();
$activesubject = new ActiveSubject();
$activesubject->clientid = $clientid;
$activesubject->TrNo = $subject->TrNo;
$activesubject->LINE = $subject->LINE;
$activesubject->period = $subject->schead->period;
$activesubject->subjectcode = $subject->subjectcode;
$activesubject->schedday = $subject->schedday;
$activesubject->schedtime = $subject->schedtime;
//remember to use schead if the value is joined from another table.
$activesubject->section = $subject->schead->section;
$activesubject->roomcode = $subject->roomcode;
$activesubject->units = $subject->units;
$activesubject->save();
//reduces the slot of ccsubject by 1
$subject->slots = $subject->slots - 1;
//never forget the saving part
$subject->save();
I am not able to use this this time because I needed to insert an array of values so as I said I opted to this.
$subjects = ActiveCurriculum::find()
->select(['scstock.*', 'schead.*'])
->leftJoin('schead', 'schead.TrNo = scstock.TrNo')
->where(['sectiongroup' => $group])
->asArray()
->all();
// $activesubject = new ActiveSubject();
$bulkInsertArray = [];
foreach ($subjects as $values) {
$bulkInserArray[] = [
'clientid' => $clientid,
'TrNo' => $values['TrNo'],
'LINE' => $values['LINE'],
'period' => $values['period'],
'subjectcode' => $values['subjectcode'],
'schedday' => $values['schedday'],
'schedtime' => $values['schedtime'],
'section' => $values['section'],
'roomcode' => $values['roomcode'],
'units' => $values['units'],
];
if (count($bulkInsertArray) > 0) {
$columnNameArray = ['clientid', 'TrNo', 'LINE', 'period', 'subjectcode', 'schedday', 'schedtime', 'section', 'roomcode', 'units'];
// below line insert all your record and return number of rows inserted
$insertCount = Yii::$app->db->createCommand()
->batchInsert('subjectcontainer', $columnNameArray, $bulkInsertArray)
->execute();
}
}
But I am not able to
$subject->slots = $subject->slots - 1;
$subject->save();
like in the first one because of the arrays, can you tell me how to do this in my second code because I need to subtract the slots column by 1 every iteration of the for loop this time. Thank you.
You can perform subtraction using single query. Something like this:
$columnToUpdate = ['slots' => new \yii\db\Expression('[[slots]] - 1')];
$condition = ['sectiongroup' => $group];
ActiveCurriculum::updateAll( $columnToUpdate, $condition );
It will execute SQL:
UPDATE `active_curriculum` SET `slots`=`slots` - 1 WHERE `sectiongroup`=1234
You just need to make correct condition that correctly selects necessary rows. Alternatively, you can collect primary keys of records (IDs) when you prepare $bulkInserArray and use them for condition:
$condition = ['id' => $subjectIDsToUpdate];
This condition will build id IN (...) automatically.
I am attempting to create a new Drupal 7 user and then assign the UID of that user to a variable. I want to store this UID so that I can create a new node and assign that user as the owner.
QUESTION: Does anyone know how to get the UID of the newly created user?
MY CODE:
// CREATE USER
$newUser = array(
'name' => $refereeUsername,
'pass' => $refereePassword,
'mail' => $refereeEmail,
'status' => 1,
'init' => $refereeEmail,
'roles' => array(
2 => 'authenticated',
53 => 'Referer',
),
);
user_save($usera, $newUser);
// MY ATTEMPT TO GET THE NEWLY CREATED USER ID
$uidn = $usera->uid;
// CREATE NODE
$node = new stdClass;
$node->type = 'referee';
$node->title = 'Referee report for xx';
$node->uid = $uidn;
$node->status = FALSE;
$node->field_testff['und'][0]['value'] = "testworked";
node_object_prepare($node);
node_save($node);
user_save() returns the user object upon successful save (the variable is sent by value, not by reference). Try this:
$account = user_save($newUser);
$uidn = $account->uid;
To solve this issue I used the user_load_by_mail() function. Using the user_save() function caused an integrity constraint violation error in my code.
$accountb = user_load_by_mail($email);
$uidn = $accountb->uid;
Documentation:
https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load_by_mail/7
I'm having an issue using the Quickbase API to perform the following:
SELECT 1, 2, 3 FROM table AA that has column BB = 1
foreach record {
Insert 1, 2, 3 into table ZZ.
}
function add_children($opportunity_id) {
global $config;
$qbc = new QuickBase($_SESSION['qb_username'] ,
$_SESSION['qb_password'],
true,
$config['AA'],
$config['debug'],
$config['app_token']);
$xml = $qbc->do_query("{'" . $config['AA'] . "'.EX.''}", 0, 0, 'a', 0, '', '');
$records = array();
foreach($xml->record as $record) {
$r = array();
$r['record_id'] = $record->record_id_;
$r['account_number'] = $record->account_number;
$records[] = $r;
$xml = $qbc->add_record($records[]);
}
}
First, I'm assuming that you're using this PHP SDK by QuickbaseAdmirer https://github.com/QuickbaseAdmirer/QuickBase-PHP-SDK. There are a few potential problems with your code.
Double check that your constructor is correct. Unless you've modified it, the Quickbase constructor in the SDK (again that I'm assuming you're using) takes user name, password, xml, database id, and then token in that order. Whatever value is in $config['debug'] may be taken as the token and the value of $config['app_token'] may be taken as your realm. Also, $config['AA'] as used in the constructor should be a string of random seeming characters like "bbqn1y5qv". Here's the constructor in the SDK for reference:
public function __construct($un, $pw, $usexml = true, $db = '', $token
= '', $realm = '', $hours = '')
Your query $xml = $qbc->do_query("{'" . $config['AA'] . "'.EX.''}", 0, 0, 'a', 0, '', ''); is not returning any records because $config['AA'] is both being used as your DBID (in the constructor) and your field ID in the query. The DBID must be a string and the field ID must be an integer that corresponds to the field you're making the query for. For example, if you wanted to return records created today your query would be '{1.IR.today}' because 1 is always the field ID for date created. It's also not returning any records because the SDK requires queries be passed as an array of arrays. So, my records created today query needs to be rewritten as:
$query= array(
array(
'fid' => '1',
'ev' => 'IR'),
'cri' => 'today'),
);
You'll also need to pass a string of period separated values to the clist parameter of the method or leave it blank for the table defaults. For example, if I wanted to get the date created and record ID for all records in this table sorted by date ascending, I would use this:
$query= array(
array(
'fid' => '3',
'ev' => 'GT'),
'cri' => '0'),
);
$xml = $qbc->do_query($query, '', '', '1.3', '1', '', 'sortorder-A');
You can read up more on the Quickbase API, and do_query specifically, here http://www.quickbase.com/api-guide/index.html#do_query.html
The add record API call takes pairs of field IDs and values. The SDK handles that by taking an array of arrays with 'fid' and 'value' pairs. Assuming you want to put the value of $record->record_id_ in field #37 and $record->account_number in field #30 your code should look like this:
foreach($xml->record as $record) {
$records= array(
array(
'fid' => '37', //Whatever field you want to store the value to
'value' => $record->record_id_),
array(
'fid' => '30',
'value' => $record->account_number),
);
$xml = $qbc->add_record($records);
}
Throw in a print_r($xml); at the end and you can see any response from Quickbase for debugging. You should get something like this for a success:
SimpleXMLElement Object ( [action] => API_AddRecord [errcode] => 0 [errtext] => No error [rid] => 81 [update_id] => 1436476140453 )
The way your code is presented, you may not get the results you expect. Your do query and add record method calls are performed on the same table and that isn't normally what someone would want. Usually, the goal is to perform a do query on one table and then use that data to add records in a different table. If that's the case, you'll need to change the database ID in your $qbc object before you preform the add record call. This is easy enough to do with $qbc->set_database_table('DBID'); where DBID is the target table ID (which should be a string of random seeming characters like "bbqn1y5qv").
Best of luck!
Here is the code:
$the_question = $_POST['question'];
$the_answer = $_POST['answer'];
$dummy_num[] = $_POST['dummy_answer_1'];
$dummy_num[] = $_POST['dummy_answer_2'];
$dummy_num[] = $_POST['dummy_answer_3'];
//Get Hidden Test ID and Q_order
$test_id = $_POST['test_id'];
$q_order = $_POST['q_order'];
//Submit Question
$data_submit_q = array (
'type' => 1,
'question' => $the_question,
'done' => 1
);
$this->db->where('test_id', $test_id);
$this->db->where('q_order', $q_order);
$this->db->update('questions', $data_submit_q);
$question_id = $this->db->insert_id();
$time_created = date('Y-m-d H:i:s');
//Submit Answer
$data_submit_a = array (
'test_id' => $test_id,
'question_id' => $question_id,
'option' => $the_answer,
'company_id' => $data['company']->id,
'job_id' => $data['session_job_id'],
'time_created' => $time_created
);
$this->db->insert('options', $data_submit_a);
$answer_id = $this->db->insert_id();
//Let question know that answer is right.
$data_submit_qr = array (
'answer_id' => $answer_id
);
$this->db->where('id', $question_id);
$this->db->where('test_id', $test_id);
$this->db->update('questions', $data_submit_qr);
Setting the answer id removes the value of the question id, then on updating the database the answer id has no value also. Even though it does right before.
The method $this->db->insert_id() retrieves the ID when performing database inserts (as the name hints).
You're using it after an update, that's why your $question_id gives problems (I think it would be set to FALSE, but I don't know for sure what does that method return when called on the wrong context). WHen you do your last update you use this as a WHERE condition, and if it is not set...
It's not that your second call to insert_id() wipes out the first, I suspect is more like the first one is already NOT SET (or FALSE)
It seems that there is a bug with insert_id, you can try using:
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$lastInsertId = $row['LAST_INSERT_ID()'];
Hope it helps