MVC 4 Retrieve db id from newly created entry - mysql

If I create a entry in a database such as this (cvmCasefile has all info needed to create the casefile):
Casefile casefile = cvm.Casefile;
casefile.ClientId = cvm.Client.ClientId;
casefile.DateSubmitted = DateTime.Now;
db.Casefiles.Add(casefile);
db.SaveChanges();
Immediately after the save call I try to retrieve this entries ID number from the database with:
int casefileId = db.Casefiles.Where(u => u.UserProfileId == casefile.UserProfileId)
.Where(c => c.ClientId == casefile.ClientId)
.Single(d => d.DateSubmitted == casefile.DateSubmitted).CasefileId;
This returns null when it is executed. I've stepped through the program and all casefile values are populated and the database has the required row inserted with a valid ID#. Is there an easier way to get the ID from the database or where did is screw-up the call to the database?

Think you may just do
var id = casefile.CasefileId;
after the SaveChanges

Related

DataTables warning: JSON data from server could not be parsed. This is a caused by a JSON formatting error in Zend framework while using group

Please help me. I am stuck with one DataTable warning like "DataTables warning: JSON data from server could not be parsed. This is a caused by a JSON formatting error." in zend framework with PHP, JSON encode.
This warning only happens when the table is empty, But This problem is only coming when I use group keyword in sql query, If I do not use group keyword then it gives only one record from the table, but table have more records also.
When I use the following query the output becomes, to show all records only the table have data, if not datatable warning will be shown.
// sql query (models/table/product.php)
public function fetchAllProductItems() {
$oSelect = $this->select()
->setIntegrityCheck(false)
->from(array("p" => "products","b" => "bid"), ('*'))
->joinLeft(array("b" => "bid"), "b.product_id=p.product_id", array('bid_id','bid_amount'))
->joinInner(array("e" => "employees"), "e.employee_id=p.employee_id",array('ename'))
->where("p.verified = ?", "Yes")
->where("p.sold_out = ?", "No")
->group('p.product_id')
->having("p.sale_end_date >= ?", date("Y-m-d"));
return $oSelect;
}
//JSON encode (Modules/sell/controllers/apicontroller)
public function getProductsAction()
{
$oProductModel = new Application_Model_Db_Table_Products();
$oSelect = $oProductModel->fetchAllProductItems();
echo Zend_Json::encode($this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name', 'brand', 'conditions', 'about','image_path', 'reserved_price', 'Max(b.bid_amount) as amount')));
}
The below query will show only one record, if more than one records are having in the table. If the table is empty then I will come "No Data available in table message will come".
// sql query (models/table/product.php)
$oSelect = $this->select()
->setIntegrityCheck(false)
->from(array("p" => "products","b" => "bid"), ('*'))
->joinLeft(array("b" => "bid"), "b.product_id=p.product_id", array('bid_id','bid_amount'))
->joinInner(array("e" => "employees"), "e.employee_id=p.employee_id",array('ename'))
->where("p.verified = ?", "Yes")
->where("p.sold_out = ?", "No")
->where("p.sale_end_date >= ?", date("Y-m-d"));

How to update a pivot table using Eloquent in laravel 5

I am new to laravel. I am working on a laravel 5 app and I am stuck here. I have 2 models as such:
class Message extends Eloquent{
public function user()
{
return $this->belongsTo('App\User', 'from');
}
public function users()
{
return $this->belongsToMany('App\User')->withPivot('status');
}
}
class User extends Eloquent {
public function messages()
{
return $this->hasMany('App\Message', 'from');
}
public function receive_messages() {
return $this->belongsToMany('App\Message')->withPivot('status');
}
}
There exist a many-to-many relationship between Message and User giving me a pivot table as such:
Table Name: message_user
Colums:
message_id
user_id
status
I have an SQL query as such:
update message_user
set status = 1
where user_id = 4 and message_id in (select id from messages where message_id = 123)
How can I translate this query to the laravel equivalent?
The code below solved my problem:
$messages = Message::where('message_id', $id)->get();
foreach($messages as $message)
$message->users()->updateExistingPivot($user, array('status' => 1), false);
You may use one of these two functions, sync() attach() and the difference in a nutshell is that Sync will get array as its first argument and sync it with pivot table (remove and add the passed keys in your array) which means if you got 3,2,1 as valued within your junction table, and passed sync with values of, 3,4,2, sync automatically will remove value 1 and add the value 4 for you. where Attach will take single ID value
The GIST: if you want to add extra values to your junction table, pass it as the second argument to sync() like so:
$message = Messages::find(123);
$user = User::find(4);
// using attach() for single message
$user->message()->attach($message->id, [
'status' => 1
]);
$message2 = Messages::find(456); // for testing
// using sync() for multiple messages
$user->message()->sync([
$message->id => [
'status' => 1
],
$message2->id => [
'status' => 1
],
]);
Here is a small example of how to update the pivot table column
$query = Classes::query();
$query = $query->with('trainees')
->where('user_id', Auth::id())
->find($input['classId']);
foreach ($query->trainees as $trainee) {
$trainee->pivot->status = 1 //your column;
$trainee->pivot->save();
}
Note: make sure your relation data must in an array
Hope its help you :)
happy coding
Laravel 5.8
First, allow your pivot columns to be searchable by chaining the withPivot method to your belongsToMany
Copied from my own code to save time
// I have 3 columns in my Pivot table which I use in a many-to-many and one-to-many-through scenarios
$task = $user->goalobjectives()->where(['goal_objective_id'=>$goal_objective_id,'goal_obj_add_id'=>$goal_obj_add_id])->first(); //get the first record
$task->pivot->goal_objective_id = $new; //change your col to a new value
$task->pivot->save(); //save
The caveat is that your pivot table needs to have a primary 'id' key.
If you don't want that then you can try the following:
$tasks=$user->posts()->where(['posts_id'=>$posts_id,'expires'=>true])->get()->pluck('id'); // get a collection of your pivot table data tied to this user
$key=join(",",array_keys($tasks->toArray(),$valueYouWantToRemove));
$tasks->splice($key,1,$newValueYouWantToInsert);
$c = array_fill(0,$tasks->count(),['expires'=>true]); //make an array containing your pivot data
$newArray=$tasks->combine($c) //combine the 2 arrays as keys and values
$user->posts()->sync($newArray); //your pivot table now contains only the values you want
4th July Update Update to above snippet.
//Ideally, you should do a check see if this user is new
//and if he already has data saved in the junction table
//or are we working with a brand new user
$count = $user->goalobjectives->where('pivot.goal_obj_add_id',$request->record)->count();
//if true, we retrieve all the ids in the junction table
//where the additional pivot column matches that which we want to update
if($count) {
$ids = $user->goalobjectives->where('pivot.goal_obj_add_id',$request->record)->pluck('id');
//convert to array
$exists = $ids->toArray();
//if user exists and both saved and input data are exactly the same
//there is no need
//to update and we redirect user back
if(array_sum($inputArray) == array_sum($exists)) {
//redirect user back
}
//else we update junction table with a private function
//called 'attachToUser'
$res = $this->attachToUser($user, $inputArray, $ids, $request->record);
}//end if
elseif(!$count) {
//we are working with a new user
//we build an array. The third pivot column must have equal rows as
//user input array
$fill = array_fill(0,count($inputArray),['goal_obj_add_id'=>$request->record]);
//combine third pivot column with user input
$new = array_combine($inputArray,$fill);
//junction table updated with 'user_id','goal_objective_id','goal_obj_add_id'
$res = $user->goalobjectives()->attach($new);
//redirect user if success
}
//our private function which takes care of updating the pivot table
private function attachToUser(User $user, $userData, $storedData, $record) {
//find the saved data which must not be deleted using intersect method
$intersect = $storedData->intersect($userData);
if($intersect->count()) {
//we reject any data from the user input that already exists in the database
$extra = collect($userData)->reject(function($value,$key)use($intersect){
return in_array($value,$intersect->toArray());
});
//merge the old and new data
$merge = $intersect->merge($extra);
//same as above we build a new input array
$recArray = array_fill(0,$merge->count(),['goal_obj_add_id'=>$record]);
//same as above, combine them and form a new array
$new = $merge->combine($recArray);
//our new array now contains old data that was originally saved
//so we must remove old data linked to this user
// and the pivot record to prevent duplicates
$storedArray = $storedData->toArray();
$user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->detach($storedArray);
//this will save the new array without detaching
//other data previously saved by this user
$res = $user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->syncWithoutDetaching($new);
}//end if
//we are not working with a new user
//but input array is totally different from saved data
//meaning its new data
elseif(!$intersect->count()) {
$recArray = array_fill(0,count($userData),['goal_obj_add_id'=>$record]);
$new = $storedData->combine($recArray);
$res = $user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->syncWithoutDetaching($new);
}
//none of the above we return false
return !!$res;
}//end attachToUser function
This will work for pivot table which doesn't have a primary auto increment id. without a auto increment id, user cannot update,insert,delete any row in the pivot table by accessing it directly.
For Updating your pivot table you can use updateExistingPivot method.

Magento add a column to sales_flat_quote table and add data

I am coming from a previous enviornment where doing things like modifying queries and adding columns was just a matter of writing the sql and executing it. However, now that I'm working in Magento I want to do things "the Magento way".
Scenario: we use paypal express, and before the controller redirects to paypal, I would really like to add a field (if not there already) in sales_flat_quote, called paypal_status - and set the value = 1 (we'll call it, sent to paypal).
On return I want to update that to either 2 or 3 (returned and pending transaction, or returned and captured transaction).
So there are two things I need to know how to do:
have something like $db->addColumn('paypal_status') where it will only add if not exists, and
write UPDATE sales_flat_quote SET paypal_status = 1 WHERE entity_id =
{whatever}
This will be inside the ...Paypal_Express class.
Open database and fire this SQL: Alter table sales_flat_quote Add paypal_status tinyint(1) NOT NULL DEFAULT 1;
Alternatively, you can write following in your SQL file (located at CompanyName\MyModuleName\sql\companyname_modulename_setup) of your custom module. This file will get executed only one time , that is the first time when the module is installed. At that time your custom column will not be there in database so it will create one.
$installer = $this;
$installer->startSetup();
$installer->run("ALTER TABLE `{$installer->getTable('sales/quote')}` ADD `paypal_status` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'My Custom Paypal Status';");
$installer->endSetup();
Clear all cahces.
To save data :
$myValue = 2;
Mage::getSingleton("checkout/cart")->getQuote()->setPaypalStatus($myValue)->save();
Mage::getSingleton("checkout/cart")->getQuote() will give you current quote.
In your sql file at CompanyName\MyModuleName\sql\companyname_modulename_setup copy the following code in order to create the column.
$installer = $this;
$installer->startSetup();
$installer->getConnection()
->addColumn($installer->getTable('sales/quote'),
'paypal_status',
array(
'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
'nullable' => true,
'comment' => 'Paypal Status',
)
);
$installer->endSetup();
Logout and login, and flush magento cache in order to add the column to the table.
The Express Checkout controller is in app/code/core/Mage/Paypal/Controller/Express/Abstract.php. If you want to add a field before the controller redirects to paypal you can modify the _initCheckout() method like this:
protected function _initCheckout()
$quote = $this->_getQuote();
if (!$quote->hasItems() || $quote->getHasError()) {
$this->getResponse()->setHeader('HTTP/1.1','403 Forbidden');
Mage::throwException(Mage::helper('paypal')->__('Unable to initialize Express Checkout.'));
}
$quote->setPaymentStatus(1); // Here is your change
$this->_checkout = Mage::getSingleton($this->_checkoutType, array(
'config' => $this->_config,
'quote' => $quote,
));
return $this->_checkout;
}

Retrieve session data Codeigniter

I'm working on a messaging system and want the user's userid to be posted to the database along with the message. Right now, the message is posting to the database, but with a user ID of 0.
How can I get the user ID from the session data to post to the database along with the message? Sidenote: I'm using Tank Auth for authentication. (From the mysql side, user_id in the message table is a foreign key referencing id in the users table).
Controller
function index() {
if ($this->input->post('submit')) {
$id = $this->input->post('user_id');
$message = $this->input->post('message');
$this->load->model('message_model');
$this->message_model->addPost($id, $message);
}
}
Model
function addMessage($id, $message) {
$data = array(
'user_id' => $id,
'message' => $message
);
$this->db->insert('message', $data);
}
For tank_auth, get the user_id using the following, and then assign that to your sessions
$user_id = $this->tank_auth->get_user_id();
Taken directly from CI's documentation:
Retrieving Session Data
Any piece of information from the session array is available using the
following function:
$this->session->userdata('item');
Where item is the array index
corresponding to the item you wish to fetch. For example, to fetch the
session ID you will do this:
$session_id = $this->session->userdata('session_id');
Note: The
function returns FALSE (boolean) if the item you are trying to access
does not exist.
So, if you have a piece of session data named user_id, you would access it like this:
$user_id = $this->session->userdata('user_id');

LINQ to SQL SubmitChanges() Inserts two Database Rows and one Child Row

I have this going me crazy,
I'm attaching a List with 1 Customer and 1 Address child record row.
Everything seems OK while debugging. 1 customer Row and 1 Address Row should inserted.
But instead I get 2 Customer Records and 1 Address Row.
I don't know why. When Attaching and looping inside the List only 1 record seen.
Any points?
[EDITED]
Code Attached:
public bool InsertUpdateCustomers(List<Customer> customerList, List<Customer> originalCustomers)
{
using (DbContext db = new DbContext(DbContext.ConnectionString))
{
db.Log = Console.Out;
List<Customer> customerCloned = new List<Customer>();
customerList.ForEach(p => customerCloned.Add(p.CloneObjectGraph()));
customerCloned.ForEach(p => p.Address =
customerList.Where(pe => pe.Id == p.Id).Single().Address.CloneObjectGraph());
customerCloned.ForEach(p =>
{
if (p.Id > 0)
{
db.Customer.Attach(p,
originalCustomers.Single(
x => x.Id == p.Id));
db.Address.Attach(p.Address,
originalCustomers.Single(
x => p.AddressId== x.AddressId).
Address);
}
});
customerCloned.ForEach(p =>
{
if (p.Id == 0)
db.Customer.InsertOnSubmit(p);
});
try
{
db.SubmitChanges(ConflictMode.ContinueOnConflict);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
I have checked the Log in the output and I see indeed 2 Inserts in the table.
I don't see nothing about the Address, but inserts correctly.
It could be the foreign key problem i don't get it.
I guess you've solved this for now but I ran into a similar issue and wanted to report back my understanding of this issue for future users.
The issue, I believe, is that you are using an existing list of Customer objects retrieved from the DB using a particular DataContext. You are then creating a new DataContext in your method and with this new DataContext, you are attaching an Address object.
This Address object (assuming has a foreign key relation with Customer) creates a new Customer object in the DB since the DataContext for which SubmitChanges is called, the originalCustomer is also treated as a new record.
In other words, to avoid these problems, you must re-use the existing DataContext using which the originalCustomer List was fetched so that inserting the child record of Address doesn't trigger an entry into the parent table.
Hope this helps.