Still stuck in update row cakephp - cakephp

I have posted a question and got help but I still dont make it.
Im trying to update a row in cakePHP 2.3.1.I have class Test extend AppModel with $validates array, and the Controller( simplified ) :
public function editstudent() {
if($this->request->data) {
$this->Test->stuId= $this->data['Test']['stuId'];
if ($this->Test->save($this->request->data)) {
$this->set('state',1);
}
}
My view after edit with suggestion from a user :D :
class Test extends AppModel {
var $name= 'Test';
var $primaryKey= 'stuId';
public $validate= array(.......);
}
I've set $primaryKey in View,set $this->Test->$primaryKey in controller but still got the error :
Database Error Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'PRIMARY' SQL Query: INSERT INTO cakePhp.tests (stuName, stuDoB, stuAdd) VALUES ('Đào Đức Anh', '2013-03-25', 'Kim Liên')
Can anyone help me out,I really need help,I'm stuck at this for 2 day and cant figure it out :(

I think you have to change the following line
$this->Test->stuId = $this->data['Test']['stuId'];
to
$this->Test->id = $this->data['Test']['stuId'];
because it is the id property that contains the primary key value.

Quick attempt:
Try changing $this->data to $this->request->data in your controller code.
More things:
Bottom line, your primary key isn't getting set.
Try using (per the CakePHP book) this syntax:
public $primaryKey = 'stuId'; //notice "public" instead of "var"
check to find out why 'studId' isn't in the data being saved.
debug($this->request->data);
My assumption is, it's not in the request data - if it were, you'd be fine.
add the studId into the form that's being submitted or
get theID into the request data any other way you see fit
Side note:
you keep saying "view", but you really mean "model".

Add Your primary key in AppModel.php
public $primaryKey='username';

Related

Access an ID of a record before its finished being created laravel

I'm trying to store the id of a record within the record. I am aware I could just use a where statement to find the last ID and increment by one but I was curious is it possible to get the ID of the record whilst its been made.
$ScreenshotOBJ = Screenshots::create([
"CollectionID" => $ScreenshotOBJ->id,
//This isn't the whole record just the important part
]);
Is this possible it throws an error saying the variable doesn't exist.
You could make the CollectionID field nullable. And then in the boot method of your Screenshots model, you can set the CollectionID like this,
protected static function boot()
{
parent::boot();
static::created(function ($screenshot) {
$screenshot->update(
['CollectionID' => $screenshot->id)]
);
});
}

Where 0 = 1 in Laravel BelongsTo Relationship Query Log

I'm just trying to use BelongsTo relationship to retrieve the records,
Here is the scheme:
roles:
- id
- title
users:
- id
- Role_ID
I'm using SQL Server for Database so the Role_ID can pointed as role_id I think :D.
and here is the code for the belongs to relationship in User Model:
public function role()
{
return $this->belongsTo('App\Role');
}
I also have tried like this:
public function role()
{
return $this->belongsTo('App\Role', 'id', 'Role_ID');
}
But whatever the parameters are it doesn't work and when I get the Query log, it looks like as:
bindings: []
query: "select * from [roles] where 0 = 1"
time: 1.49
Here is how I try to access the relation in the Controller:
User::with(['role'])->get($someColumns)
I'm just fighting with this problem for many times but don't know where the issue is.
Any help is appreciated.
Thanks everybody.
You have to include the foreign key in get() columns
User::with(['role'])->get(Role_ID, OthersColumns)
Try this relationship in your model.
public function role()
{
return $this->belongsTo('App\Role', 'Role_ID','id');
}
Thanks guys, #Dilip hint helped me to solve the problem.
Please see my updated question this line:
User::with(['role'])->get($someColumns)
Actually the problem was with $someColumns, because when I was mentioning the name of some columns in get, it was causing the issue but when I replaced it with the following:
User::with(['role'])->get()
It worked,
So the simple solution is to not mention the columns name when getting with relationship belongsTo

Add table name to each select field in query, in agile tookit

I have a problem with certain generated query, the query does an inner join with a table that has some same field.
How can I have the query with the table name in each field, basically what i want is that:
Convert this:
select "list_id", "date_time","plate"...
TO:
select register."list_id", register."date_time",register."plate"...
I think with alias to the field name also could be accomplished but i dont know how to add the alias in atk4
If someone wants to see the full query and atk error:
Application Error: Database Query Failed
Exception_DB, code: 0
Additional information:
pdo_error: SQLSTATE[42702]: Ambiguous column: 7 ERROR: column reference "date_time" is ambiguous LINE 1: select "date_time","plate",(select "name" from "lane" whe... ^
mode: select
params:
query: select "date_time","plate",(select "name" from "lane" where "register"."lane_id" = "lane"."id" ) "lane",(select "name" from "camera" where "register"."camera_id" = "camera"."id" ) "camera",(select "detail"."id" from "detail" where "register"."detail_id" = "detail"."id" ) "detail","id","lane_id","camera_id","detail_id" from "register" inner join "detail" on "detail"."id" = "register"."detail_id" order by (select "detail"."id" from "detail" where "register"."detail_id" = "detail"."id" )
This is how im making the model. This model has 3 related fields in other tables, with those, all is OK. But i want to have one more field (field name from table List), and List is not directly related to Register, is only related throught Detail. So i have to get it throught Register->Detail->List..
table Register(id, plate, detail_id,..)---->hasOne(detail_id)-->table Detail(id, list_id, date..)---->hasOne(list_id)---->table List(id,name,..)
model class:
class Model_Register extends Model_Table {
public $table='register';
function init(){
parent::init();
$this->addField('date_time')->sortable(true)->defaultValue(date('Y-m-d H:m:i'))->type('date')->mandatory(true);
$this->addField('plate')->sortable(true)->mandatory(true);
$this->hasOne('Lane', 'lane_id')->sortable(true)->system(true);
$this->hasOne('Camera', 'camera_id')->sortable(true);
$this->hasOne('Detail', 'detail_id')->sortable(true);
}
}
And after in the page class i do the join, yes I know is detail at this moment is redudant im only trying...
$register = $crud->setModel('Register');
$q = $register->_dsql();
$q->join('detail', 'detail_id', 'inner');
$q->join('list', 'list_id', 'inner');
How can I have this field from the List field?? Any solution will be welcomed..
Thanks in advice!! Im breaking my head with this! ;)
Thanks for your time guys, finally I found the solution with the called: Chained joins
Example from documentation:
$perm = $this->join('permission');
$res = $perm->join('resource');
Belive or not that was my real problem! Thanks all anyway
try to add 'table_alias' property for your Models
class Model_Yours extends Model_Table {
public $table_alias = '_alias';
}
Default value for this property is null - link
So if you add any value it can be used here
Not sure if this will help :(
$t1 = $this->add('Main_Table');
$t2 = $t1->leftJoin('joined_table_name');
$t2->addField('joined_table_field_ALIAS','joined_table_field_REALNAME');
check SQL_Model::addField() method here

CakePHP Not Saving BelongsTo Key

I'm trying to save a record that belongs to another model. Yet, I get an error that the foreign key is missing. The CakePHP docs show examples of this working but I can't get it to work.
Here is the Form:
echo $this->Form->create('Message', array('action'=>'add'));
echo $this->Form->hidden('Ticket.id');
echo $this->Form->input('Message.message');
echo $this->Form->submit('Save Message');
echo $this->Form->end();
Here is what is returned to the controller upon submit:
Array(
[Ticket] => Array
(
[id] => 2
)
[Message] => Array
(
[message] => Message text
)
)
Here is my Message model:
class Message extends AppModel {
public $belongsTo = array('Ticket');
}
Here is my Ticket model:
class Ticket extends AppModel {
public $hasMany = 'Message';
}
Here is my controller logic:
$this->Message->save($this->request->data);
Here is the error message I receive:
Error: SQLSTATE[HY000]: General error: 1364 Field 'ticket_id' doesn't have a default value
The CakePHP documents are pretty clear that Cake will grab the id from the Ticket array. The only way I can get this to work is if I manually assign the ticket id to the message array.
$this->request->data['Message']['ticket_id'] = $this->request->data['Ticket']['id']
I shouldn't have to do that. Where's the magic? I've read at least 20 similar posts but none exactly like this (probably because this is so basic that nobody has this problem because it works for them).
I'm using version 2.4.2
Thanks for any help.
Don't use Model::save() in this case, the reason is that you also want to save associated data, in order for you save data for the main model along with its associated models you need to use Model::saveAssociated().
Your controller should be looking like this
$this->Message->saveAssociated($this->request->data);

What is the equivalent to getLastInsertId() in Cakephp?

If I do getLastInsertId() immediately after a save(), it works, but otherwise it does not. This is demonstrated in my controller:
function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->getLastInsertId(); //here it works
}
function insertformname() {
echo $this->Form->getLastInsertId(); //this doesnt echo at all
}
Please suggest a way to get the functionality I want.
CakePHP has two methods for getting the last inserted id: Model::getLastInsertID() and Model::getInsertID().
Actually these methods are identical so it really doesn't matter which method you use.
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
This methods can be found in cake/libs/model/model.php on line 2768
Just use:
$this->Model->id;
In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id
id - Value of the primary key ID of
the record that this model is
currently pointing to. Automatically
set after database insertions.
Read more about model properties in the CakePHP API Docs: http://api.cakephp.org/2.5/class-AppModel.html
Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id
After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?
Can you explain the flow of your application and how it relates to your problem?
You'll need to do an insert (or update, I believe) in order for getLastInsertId() to return a value. Could you paste more code?
If you're calling that function from another controller function, you might also be able to use $this->Form->id to get the value that you want.
Try using this code in your model class (perhaps in AppModel):
function get_sql_insert_id() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
return $db->lastInsertId();
}
Caveat emptor: MySql's LAST_INSERT_ID() function only works on tables with an AUTO_INCREMENT field (otherwise it only returns 0). If your primary key does not have the AUTO_INCREMENT attribute, that might be the cause of your problems.
this is best way to find out last inserted id.
$this->ModelName->getInsertID();
other way is using
$this->ModelName->find('first',array('order'=>'id DESC'))
There are several methods to get last inserted primary key id while using save method
$this->loadModel('Model');
$this->Model->save($this->data);
This will return last inserted id of the model current model
$this->Model->getLastInsertId();
$this->Model-> getInsertID();
This will return last inserted id of model with given model name
$this->Model->id;
This will return last inserted id of last loaded model
$this->id;
Try to use this code. try to set it to a variable so you can use it in other functions. :)
$variable = $this->ModelName->getLastInsertId();
in PHP native, try this.
$variable = mysqli_insert_id();
This will return last inserted id of last loaded model
$this->id;
This will return last inserted id of model with given model name
$this->Model->id;
This will return last inserted id of the model current model
CakePHP has two methods for getting the last inserted id:
Model::getLastInsertID() and Model::getInsertID().
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
Below are the options:
echo $this->Registration->id;
echo $this->Registration->getInsertID();
echo $this->Registration->getLastInsertId();
Here, you can replace Registration with your model name.
Thanks
Use this one
function designpage() {
//to create a form Untitled
$this->Form->saveField('name','Untitled Form');
echo $this->Form->id; //here it works
}
You can get last inseted id with many ways.Like Model name is User so best way to fetch the last inserted id is
$this->User->id; // For User Model
You can also use Model function but below code will return last inserted id of model with given model name for this example it will return User model data
$this->User->getLastInsertId();
$this->User->getInsertID();
When you use save(), the last insert ID is set to the model’s $id property. So:
if ($this->Model->save()) {
printf('Last insert ID was %s', $this->Model->id);
}
Each time a save method is called on a model, cake internally calls Model::getLastInsertId() and stores the result into model class attribute id, so after calling save() it is not necessary to call Model::getLastInsertId() or inserId(), as tha value can be directly accessed like this
$id = $this->id;// within a model
$id = $this->{$this->modelName}->id;// in a controller
After insertion of data, we can use following code to get recently added record's id:
$last_insert_id=$this->Model->id;
each time you perform an insert operation on any model, cake internally fetchesthe last insert Id and Sets to Model->id attribute.
so one can access it directly by $Model->id;,
no need to query again for lastInsertId.
I think it works with getLastInsertId() if you use InnoDB Tables in your MySQL Database. You also can use $this->Model->id
$Machinedispatch =
$this->Machinedispatch->find('first',array('order'=>array('Machinedispatch.id DESC')));
Simplest way of finding last inserted row. For me getLastInsertId() this not works.
Actually you are using the getLastInsertId or getInsertId in a wrong manner.
getLastInsertId() is meant to work only after save() method.
It will even not work after a manual insert, as cake engine is storing the mysql_insert_id under $this->_insertID inside the save method which can be retrieved via the getLastInsertId or getInsertId.
Now in your case
$this->Model->id
OR
$this->Model->find('first',array('order'=>'id DESC'))
Will do.
This is interesting, I also stumbled upon this issue. What you asked perhaps how to get the last ID of a certain model regardless of it's state, whether it's just been inserted or not. To further understand what getInsertID does, we need to take a look at the source:
Link 1: http://api20.cakephp.org/view_source/model#line-3375
public function getInsertID() {
return $this->_insertID
}
Yup, that's the only piece of code inside that function. It means that cakephp caches any last inserted ID, instead of retrieve it from the database. That's why you get nothing if you use that function when you haven't done any record creation on the model.
I made a small function to get the last ID of a certain table, but please note that this should not be used as a replacement of getLastID() or getLastInsertID(), since it has an entirely different purpose.
Add the function lastID() to the AppModel as shown below so that it can be used system wide. It has it's limit, which can't be used on model with composite primary key.
class AppModel extends Model {
public function lastID() {
$data = $this->find('first',
array(
'order' => array($this->primaryKey . ' DESC'),
'fields' => array($this->primaryKey)
)
);
return $data[$this->name][$this->primaryKey];
}
}
Original Source : Class Model
In CakePHP you can get it by:
Model::getInsertID() //Returns the ID of the last record this model inserted.
Model::getLastInsertID() //Alias to getInsertID().
$this->Model->field('id', null, 'id DESC')

Resources