yii2 string validation using substr() in comparing attributes of two related model - arrays

I have this two table:
Region table
create table if not exists Region (
id int(2) unsigned not null auto_increment,
name varchar(40) unique not null,
code varchar(9) not null,
primary key(id)
);
Province table:
create table if not exists Province (
id int(2) unsigned not null auto_increment,
region_id int(2) unsigned not null,
name varchar(40) unique not null,
code varchar(9) not null,
primary key(id),
key region_id(region_id),
constraint province_region_id foreign key(region_id) references region(id)
);
sample data:
region_code: 010000000
province_code: 010100000
they are related coz they have the same first two character
ive created a partial custom validation but i cant finish it and even don't know if using substr() with arrayhelper combination is okay
public function modelCodeValidator()
{
$regCode=>substr([Arrayhelper::map(Region::find()->all()->,'id','code')],2);// specifying first two character of region.code
$provCode=>substr('code',2);//specifying first two character of province.code
return [$regCode=$provCode];
}
on this custom validation, rule() would be:
['code','compare','modelCodeValidator' don't know next]
first two character of region_code should match/equal to the first two character of province_code. by doing this user will notified that they could only enterered province code belonging to a particular region.please help

Try by something like this..
public function rules()
{
return [
['code', 'modelCodeValidator'],
];
}
public function modelCodeValidator($attribute, $params)
{
// Write your coding stuff here
if (YourModelName::findOne(['your_model_field'=> $attribute]) {
$this->addError($attribute, \Yii::t('view', 'The fields don't match.'));
}
}
take a look here :->
http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation

Related

Go Gorm: Foreign key not present in table creation

I'm working on a Gin app using Gorm ORM (I'm new to both of them). I've got the following model:
type Record struct {
Barcode string `json:"barcode" gorm:"size:48;unique;not null" sql:"index"`
Name string `json:"name" gorm:"size:160;unique;not null"`
Artist Artist `gorm:"foreignKey:ArtistID""`
ArtistId uint
Category Category `gorm:"foreignKey:CategoryID"`
CategoryId uint
NumOfRecords int `json:"num_of_records" gorm:"not null"`
OriginalReleaseDate time.Time `json:"original_release_date" gorm:"default:null"`
ReissueReleaseDate time.Time `json:"reissue_release_date" gorm:"default:null"`
SideColor string `json:"side_color" gorm:"default:null"`
BarcodeInRecord bool `json:"barcode_in_record" gorm:"default=true"`
gorm.Model
}
As you can see there are two fields with two foreign keys: Artist and Category.
Here's those models:
type Category struct {
Name string `json:"name" gorm:"size:60;unique;not null"`
Description string `json:"description" gorm:"size:120"`
Parent uint `json:"parent" gorm:"default:null"`
Active bool `json:"active" gorm:"default:true"`
gorm.Model
}
type Artist struct {
Name string `json:"name" gorm:"size:120;unique;not null"`
Type string `json:"type" gorm:"default:null"`
CountryOfOrigin string `json:"countryOfOrigin" gorm:"default:null"`
gorm.Model
}
category_id and artist_id columns are being created but they are not referencing the other tables two tables:
I've tried to define those fields using AssociationForeignKey:Refer. I also tried to change the foreign key name to simply ID since that's the name that GORM assigns to primary keys but none of those thinks have worked.
What am I missing?
IMO Gorm docs are pretty lousy. From another SO question (Gorm Golang orm associations) it is said that:
it doesn't (create FKs when migrations run). If you want Foreign Key in DB, you need explicitly write something like db.Model(&Place{}).AddForeignKey("town_id", "towns(id)", "RESTRICT", "RESTRICT") during your migrations.

Yii2 return single value of attribute on condition

I have these tables in the database:
user : userid (primary Key), professionid, etc,
profession : professionid (primary Key), classid, etc,
class : classid (primary key), etc,
In model of User, I create function,
public function getClassid()
{
return 1;
}
How can I replace 1 to value of classid in table of profession, where userid is current logged user?
Use
return model->profession->classid
This should work
public function getClassid()
{
$profession = Profession::findOne(['professionid' = > $this->profession_id])
return $profession->classid;
}
This returns the value of the attribute classid which is stored in the table Profession where the professionid is the same and the professionid of the current User model.
Hope this helps

CakePHP 3.x Query many Table objects with Pagination

Context:
I'm working with CakePHP 3.x and I'm trying to build an ORM query with pagination. I have the tables Users, Topics and Areas. User can have many topics but just one area. This is the db model:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
);
CREATE TABLE topics (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
name VARCHAR(255),
description TEXT,
FOREIGN KEY user_key (user_id) REFERENCES users(id)
);
CREATE TABLE areas (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
UNIQUE KEY (title)
);
CREATE TABLE users_areas (
user_id INT NOT NULL,
area_id INT NOT NULL,
PRIMARY KEY (user_id, area_id),
FOREIGN KEY area_key(area_id) REFERENCES areas(id),
FOREIGN KEY user_key(user_id) REFERENCES users(id)
);
What I need
I need to get all the Topics filtered by an area given.
I'm trying the next:
//1. get the area from the url (OK)
$area = $this->request->getQuery('area');
//2. Get the area from db to get the id
$myarea = $this->Areas->find()->where(['title' => $area])->first();
//3. Get all the users related to the area given
$users = $this->Users->find()->matching('Areas', function ($q){
return $q->where(['Areas.id' => $myarea->id]);
});
//4. Get the Topics and Paginate
$topics = $this->paginate($this->Topics->find('all')->innerJoinWith('Users', function ($q){
return $q->where(['User.id' => $myarea->id]);
}));
//5. Set the topics (OK)
$this->set(compact('topics'));
$this->set('_serialize', ['topics']);
I got tons of errors and I'm not sure how to build the query properly.
At first glance, there's at least one mistake:
$myarea is invisible inside anonymous function.
If You wanna use $myarea inside lambda function, You should inherit this variable from parent scope: use($var).
http://php.net/manual/en/functions.anonymous.php example #3
$users = $this->Users->find()->matching('Areas', function ($q) use ($myarea) {
return $q->where(['Areas.id' => $myarea->id]);
});
$topics = $this->paginate($this->Topics->find('all')->innerJoinWith('Users', function ($q){
return $q->where(['User.id' => $myarea->id]);
}));

Getting the generated key for a multi-column primary key in JDBC

I want to get the generated key from an insert.
My code:
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet generatedKeys = stmt.getGeneratedKeys();
int columnCount = generatedKeys.getMetaData().getColumnCount();
if (generatedKeys.next()) {
do {
for (int i=1; i<=columnCount; i++) {
String key = generatedKeys.getString(i);
System.out.println("KEY " + generatedKeys.getMetaData().getColumnName(i) + " = " + key);
}
} while(generatedKeys.next());
}
This works fine.
My question is now: When I have a table with a multiple primary key, the value is always null. Why is this so?
The getGeneratedKeys() method is intended to return the key values that are automatically generated by the database when inserting into a table with a single "Identity" column (a.k.a. "AutoIncrement", "AutoNumber", and probably key values generated by a Sequence as well).
Depending on the implementation details of the JDBC driver, it might be possible to retrieve other automatically-generated primary key values, e.g., if a multi-column primary key value was assigned by an INSERT trigger or some other mechanism. However, that is not particuarly likely and certainly not something that you could count on.
And of course, if the primary key value is not automatically generated (as in your case) then it should come as no surprise that getGeneratedKeys() does not return anything because there is nothing to return.

One to Many relationship using breezejs

I have the following one to many relationship setup between two tables (Case and Recipient)
Case table has one primary key which is identified as an identity (auto-increment) tblRecipient has one primary key which is identified as an identity (auto-increment),and a foreign key relationship with Case.
Case table and related tblRecipient data is pulled:
function searchCases(caseID, caseNum)
{
var qPredicate;
if (caseID != '')
{
qPredicate = new breeze.Predicate("pkCaseID", "==", parseInt(caseID));
}
else if (caseNum != null)
{
qPredicate = new breeze.Predicate("CaseNumber", "Contains", caseNum);
}
var query = breeze.EntityQuery
.from("case")
.where(qPredicate)
.expand("tblRecipients")
return manager.executeQuery(query);
}
When a button is pressed to add a new recipient, the following code is used to create a new recipient entity:
function createNewRecipient(CaseID)
{
var recipientEntityType = manager.metadataStore.getEntityType("tblRecipient");
var newRecipient = manager.createEntity(recipientEntityType, {fkCaseID: CaseID});
return newRecipient;
}
This code returns this error:
Error: Cannot attach an object to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'
The AutoGeneratedKeyType in the metadata shows None instead of Identity as in the Case table. We are not sure what we need to change or how to really debug this. Any help would be appreciated.

Resources