set id value in AUTO_INCREMENT field with laravel - mysql

I have tried to set value id of new row in laravel 5 , by Point::create($value) and new Point($value) the $value contains a id value and this id doesn't exist in mysql db.
and every time I try the new row has got a auto id not that in $value

Add id in your fillable array in Point model class.
protected $fillable = [
'id'
];

You need to set a custom primary key with:
protected $primaryKey = 'custom_key';
If you don't have PK, do this:
protected $primaryKey = null;
public $incrementing = false;
Also, remove it from fillable() array. In this case, id will be ignored.
From the docs:
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.
In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.

If you don't want to make id fillable, than you can use next instead of Point::create($value):
$point = Point::make($value);
$point->id = $value['id'];
$point->save();
Also you can Point::unguard() to temporarily disregard the fillable status of fields and make id temporary fillable.

Related

Designing JPA Entity for Database Table

I am designing a voting application and designed a database with 2 tables - State and District.
The two tables are -
State details table
State_ID NUMBER(3)
State_name VARCHAR2(30)
PRIMARY KEY(State_ID)
District details table
District_ID NUMBER(3)
State_ID NUMBER(3)
District_name VARCHAR2(30)
PIN_Code NUMBER(6)
PRIMARY KEY(District_ID)
UNIQUE(State_ID, District_name)
FOREIGN KEY(State_ID)
As two states can have a district with same name, I am considering the combination of State ID and District name as UNIQUE by combination.
Now I have to design JPA Entities for these two tables, but I am unable to design because, in the database design, the District table has State ID in it as Foreign Key, but when it comes to designing entities having a State object inside District sounds meaningless, because if I keep HAS-A relationship in my mind, then District doesn't have a State in it. A State HAS-A list of Districts. This is not in accord with the above database design.
Can someone please help me in designing JPA Entities for this. Please suggest if the database design needs modification too.
Thanks.
An example JPA approach based on Rick's proposal:
#Entity
#Table(name = "States")
public class State {
#Id
#Column(nullable = false, columnDefinition = "CHAR(2) CHARACTER SET ascii")
private String code;
#Column(nullable = false, length = 30)
private String name;
#OneToMany(mappedBy = "state")
private Collection<District> districts;
public State() { }
// getters, setters, etc.
}
#Entity
#Table(name = "Districts", uniqueConstraints = {
#UniqueConstraint(columnNames = { "state_code", "name" })
})
public class District {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false, columnDefinition = "SMALLINT UNSIGNED")
private short id;
#Column(name = "state_code", nullable = false,
columnDefinition = "CHAR(2) CHARACTER SET ascii")
private String code;
#Column(length = 30)
private String name;
#ManyToOne
#JoinColumn(name = "state_id")
private State state;
public District() { }
// getters, setters, etc.
}
NOTE: due to usage of columnDefinition attribute the above entities are not portable across databases.
CREATE TABLE States (
code CHAR(2) NOT NULL CHARACTER SET ascii,
name VARCHAR(30) NOT NULL,
PRIMARY KEY(code)
);
CREATE TABLE Districts
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
state_code CHAR(2) NOT NULL CHARACTER SET ascii,
...
PRIMARY KEY(id),
UNIQUE (state_code, name)
);
Notes:
* May as well use the standard state codes (AK, AL, ...) if you are talking about the US.
* Probably the only purpose of States is to spell out the name.
* I was explicit about ascii in case your table defaults to utf8.
* MySQL uses VARCHAR, not VARHAR2.
* You could get rid of Districts.id and have simply PRIMARY KEY(state_code, name), but I am guessing you have a bunch of other tables that need to join to this one, and a 2-byte id would be better than the bulky alternative.

Yii relation — MySQL foreign key

Tables in MySQL:
field:
id pk
field_option
id pk
feild_id int(11)
ALTER TABLE `field_option` ADD CONSTRAINT `option_field` FOREIGN KEY ( `feild_id` ) REFERENCES `agahi_fixed`.`field` (
`id`
) ON DELETE CASCADE ON UPDATE RESTRICT;
Relation Field model:
return array(
'fieldOption' => array(self::HAS_MANY, 'FieldOption', 'feild_id'),
);
Relation FieldOption model:
return array(
'feild' => array(self::BELONGS_TO, 'Field', 'feild_id'),
);
In controller:
if(Field::model()->exists('cat_id = :catId', array(":catId"=>$_POST['catid']))){
$criteria=new CDbCriteria;
//$criteria->select='*';
$criteria->condition='cat_id=:catId';
$criteria->params=array(':catId'=>$_POST['catid']);
$criteria->with = 'fieldOption';
$field=Field::model()->findAll($criteria);
header('Content-type: application /json');
$jsonRows=CJSON::encode($field);
echo $jsonRows;
}
but it does not work with just select records in field table.
Why?
this way you won't achive what your looking for,
when you fetch your records using with it will fetch associated records, meaning : eager loading not lazy, but when you json encode your model, It will get attributes of your main model, not any relations, If you want any related data to get encoded with the model, you have to explicitly say so. I suggest make an empty array :
$result = array();
make a loop over your model and append to this result, from model to related model
foreach($field as $model)
{
$record = $model->attributes; // get main model attributes
foreach($model->fieldOption as $relation)
$record['fieldOption'][] = $relation->attributes; // any related records, must be explicitly declared
$result[] = $record;
}
now you have exactly what you need, then echo it
echo CJSON::encode($result);

The INSERT statement conflicted with the FOREIGN KEY constraint2

The INSERT statement conflicted with the FOREIGN KEY constraint "fk_JOB_POSTING_CLIENT". The conflict occurred in database "ResLand", table "dbo.CLIENT", column 'ID'. The statement has been terminated.
i got above exception message while i am inserting the data in job posting screen
my database design for job_posting table is:
INSERT INTO [dbo].[JOB_POSTING]
([COMP_ID]
,[RES_ID]
,[RES_TYPE]
,[CONTACT_NAME]
,[CONTACT_INFO]
,[TITLE]
,[DESCR]
,[PREREQUISITES]
,[SKILLS]
,[JOB_TYPE]
,[LOCATION]
,[DURATION]
,[POST_DT]
,[POST_END_DT]
,[POSITIONS_CNT]
,[CLIENT_ID]
,[CATEGORY]
,[RATE]
,[PERKS]
,[STAT]
,[IS_DELETED]
,[CR_BY]
,[DT_CR]
,[MOD_BY]
,[DT_MOD])
in my controller i wrote the code like this :
[ValidateInput(false)]
//[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult PostJob(PostJobModel model, string btn)
{
if (btn == "Save")
{
JOB_POSTING jobPost = new JOB_POSTING();
jobPost.RES_ID = RL_Constants.RES_ID;
jobPost.RES_TYPE = RL_Constants.RES_TYPE;
jobPost.COMP_ID = RL_Constants.COMP_ID;
jobPost.POST_DT = Convert.ToDateTime(model.POST_DT);
jobPost.POST_END_DT = Convert.ToDateTime(model.POST_END_DT);
jobPost.POSITIONS_CNT = Convert.ToInt32(model.POSITIONS_CNTS);
jobPost.JOB_TYPE =Convert.ToString(model.JOB_TYPE);
jobPost.DURATION = model.DURATION;
jobPost.CATEGORY = Convert.ToString(model.CATEGORY_ID);
jobPost.PREREQUISITES = model.PREREQUISITES;
jobPost.LOCATION = model.LOCATION;
jobPost.RATE = model.RATE;
//CLIENT=model.CLIENT_ID
//CLIENT_ID=(model.CLIENT_ID)
jobPost.TITLE = model.POST_TITLE;
jobPost.DESCR = Regex.Replace(model.DESCRIPTION, #"<[^>]+>| ", "");
jobPost.CONTACT_NAME = model.CONTACT_PERSON;
jobPost.CONTACT_INFO = model.CONTACT_PHONE + "/" + model.CONTACT_EMAIL;
jobPost.SKILLS = model.SKILLS;
jobPost.PERKS = model.PERKS;
jobPost.DT_CR = DateTime.Now;
jobPost.CR_BY = RL_Constants.USER_NAME;
jobPost.STAT = "ACTIVE";
jobPost.IS_DELETED = "N";
reslandentity.JOB_POSTING.Add(jobPost);
reslandentity.SaveChanges();
}
return RedirectToAction("JobSearchList", "Employer");
}
where is the problem
The error message says that the client Id you're using doesn't exist in the Client table. Are you setting the cliendId fk reference correctly? In the code you've posted the setting of clientId has been commented out. This means that the clientId = 0 (if it's an int), and I bet you don't have any clients with id = 0.
---- Update -----
As your clientId = 0 it tries to make a fk relationship to the client table, which fails. You said you didn't want to use the clientId at this point and that the clientId column was nullable. I'm not sure why it's assigned the 0 value, but just to check that it's working you should do a clientId = null in your mapping. This should prevent EF from trying to make a fk relationship.

JPA Primary Key in separate sequence tables

I have multiple entities annotated with the following:
#TableGenerator(name = "XXX_Gen", table = "XXX_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL")
#GeneratedValue(strategy = GenerationType.TABLE)
#Id
private String id;
I am using MySQL behind the scenes with eclipselink and the problem is that regardless of the values that I enter in the name and table MySQL always just uses a single table called 'SEQUENCE' to increment the PK's values.
Normally this isn't an issue except I have a specific case where I need an entity to have its own incremental sequence.
I wasn't specifying the generator! It should be;
#TableGenerator(name = "XXX_Gen", table = "XXX_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL")
#GeneratedValue(strategy = GenerationType.TABLE, generator="XXX_Gen")
#Id
private String id;
I think I need another cup of coffee!

ZF last insert id gives me back '0'

When I try to use the function '->lastInsertId()' to retrieve the lat ID of a table I get back '0'.
I can't find the solution. My table is an autoincrement
I try to get it in the controller with this code.
$reviews = new Application_Model_DbTable_Reviews();
$lastId = $reviews->getAdapter()->lastInsertId();
echo $lastId;
I hope someone can help me.
With kind regards,
Nick
Well this stuff is not mention in docs but it works for e.g
if you have table name 'Book' with PK book_id , FK user_id and 'User' table with PK user_id
<<Book>>
*book_id
title
user_id
<<User>>
*user_id
name
age
then
$userTb = new Model_DbTable_User();
$user = $userTb->createRow();
$user->name = "jason";
$user->age = 25;
$user->save();
//well after saving the record ZF populates PK for you so now you have read only access to auto incremented PK simply by $userTb->user_id;
so
$bookTb = new Model_DbTable_Book();
$book = $bookTb->createRow();
$book->title = 'php';
$book->user_id = $user->user_id;
$bookId = $book->save(); // this is another way of accessing auto generated PK at insert tim .