i am having some throuble building a simple Poll application in Yii.
I have the following tables:
create table poll (
id integer not null auto_increment,
title varchar(255) not null,
views integer not null default 0,
created_at timestamp not null default NOW(),
PRIMARY KEY(id)
);
create table choice (
poll_id integer not null,
choice varchar(200) not null,
votes integer not null default 0
);
I have an ActiveRecord for Poll defined as:
class Poll extends CActiveRecord
{
...
public function relations()
{
return array(
'choices'=>array(self::HAS_MANY, 'Choice', 'poll_id'),
);
}
...
}
However when I use the following code:
$p = Poll::model()->findByPk($id)->with('choices')->findAll();
It gives me the traceback:
Invalid argument supplied for foreach()
#0
+ /home/william/scm/bmbraga/clickpoll/yii/framework/db/ar/CActiveFinder.php(791): CJoinElement->populateRecord(CJoinQuery, array("1", "0", "", "2011-02-28 13:11:41", ...))
#1
+ /home/william/scm/bmbraga/clickpoll/yii/framework/db/ar/CActiveFinder.php(736): CJoinElement->populateRecord(CJoinQuery, array("1", "0", "", "2011-02-28 13:11:41", ...))
#2
+ /home/william/scm/bmbraga/clickpoll/yii/framework/db/ar/CActiveFinder.php(395): CJoinElement->runQuery(CJoinQuery)
#3
+ /home/william/scm/bmbraga/clickpoll/yii/framework/db/ar/CActiveFinder.php(72): CJoinElement->find(CDbCriteria)
#4
+ /home/william/scm/bmbraga/clickpoll/yii/framework/db/ar/CActiveRecord.php(1242): CActiveFinder->query(CDbCriteria, true)
#5
+ /home/william/scm/bmbraga/clickpoll/yii/framework/db/ar/CActiveRecord.php(1323): CActiveRecord->query(CDbCriteria, true)
#6
+ /home/william/scm/bmbraga/clickpoll/poll/protected/controllers/PollController.php(156): CActiveRecord->findAll()
Anyone have any idea what i have been doing wrong? I am quite new to Yii
Thank you
Ok, i found out the problem.
The poll table needs a primary key.
Related
Given the following example for an Entity-Definition, there is a foreign key defined. As a developer and database engineer i would expect that the command dal:create:schema would also create the expected foreign keys. But this is not the case.
return new FieldCollection([
(new IdField('id', 'id'))->addFlags(new PrimaryKey(), new Required()),
(new LongTextField('comment', 'name'))->addFlags(new Required()),
(new FkField('order_id', 'orderId', OrderDefinition::class))->addFlags(new Required()),
new OneToOneAssociationField('order', 'order_id', 'id', OrderDefinition::class, false),
new CreatedAtField(),
new UpdatedAtField()
]);
Instead this is the result:
CREATE TABLE `order_refund` (
`id` BINARY(16) NOT NULL,
`comment` LONGTEXT NOT NULL,
`order_id` BINARY(16) NOT NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3) NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
However, it seems like that ManyToOneAssociations will add foreign keys. Is there something missing in the entity definition?
The command you mentioned is using the SchemaGenerator which has a method to generate Foreign keys:
\Shopware\Core\Framework\DataAbstractionLayer\SchemaGenerator::generateForeignKeys
Looking at this method it seems to work only fields of the type ManyToOneAssociationField
private function generateForeignKeys(EntityDefinition $definition): string
{
$fields = $definition->getFields()->filter(
function (Field $field) {
if (!$field instanceof ManyToOneAssociationField) {
return false;
}
return true;
}
);
I also think it is a shortcoming of this function that it does not generate foreign keys for fields of the type OneToOneAssociationField. Maybe you can try to adjust this filtering and see if it works and make a pull request on GitHub for the benefit of yourself and other developers?
I am creating a new project and using Spring Data JPA to create some REST endpoints.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
I am able to put and persist to my primary class (customer), which works as long as the json file does not have any oneToMany data. However, when posting to customer, if there is oneToMany data I am getting errors.
The errors relate to the foreign key being null when trying to persist. I am not sure how Spring Data JPA should be using the annotation to let hibernate know what the value of the foreign key should be.
I have looked at numerous bi-directional OneToMany examples, as well as examples for creating foreign keys and have tried a number of modifications without success.
I also tried to use the spring.jpa.hibernate.ddl-auto=update to help create and update the database schema without any luck.
The customer
#Entity
#Table(name="customer")
#EntityListeners(AuditingEntityListener.class)
public class Customer extends Auditable<String> {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer", cascade={CascadeType.ALL})
private List<EmailAddress> emailAddresses;
.......
The emails
#Table(name="email_address")
#EntityListeners(AuditingEntityListener.class)
public class EmailAddress extends Auditable<String> {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="email_type")
private byte emailType;
#Column(name="email")
private String email;
#ManyToOne(fetch=FetchType.LAZY, cascade={CascadeType.ALL})
#JoinColumn(name="customer_id")
#JsonIgnore
private Customer customer;
.....
The postman json test
{
"id": 1,
"firstName": "Bobby",
"lastName": "Smith",
"emailAddresses": [
{
"id": 1,
"emailType": 1,
"email": "bobby#bobby.com",
},
{
"id": 2,
"emailType": 1,
"email": "bobby#gmail.com",
}
]
}
BTW, I have confirmed that within the customer controller, that the emails are included in the request body of customer.
The customer controller
#PutMapping("/customers")
public Customer updateCustomer(#RequestBody Customer theCustomer) {
System.out.println("****email count "+theCustomer.getEmailAddresses().size());
for(EmailAddress index: theCustomer.getEmailAddresses()) {
System.out.println(index.toString());
}
customerService.save(theCustomer);
return theCustomer;
}
The customer service
#Override
public void save(Customer theCustomer) {
//Validate the input
if(theCustomer == null) {
throw new CustomerNotFoundException("Did not find the Customer, was null...");
}
customerRepository.save(theCustomer);
}
MySQL Script
--
-- Table structure for table `customer`
--
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(24) COLLATE utf8_bin NOT NULL,
`last_name` varchar(24) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Primary Customer Table';
--
-- Table structure for table `email_address`
--
DROP TABLE IF EXISTS `email_address`;
CREATE TABLE `email_address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email_type` tinyint(4) unsigned NOT NULL COMMENT 'email type',
`email` varchar(128) COLLATE utf8_bin NOT NULL COMMENT 'email address',
`customer_id` int(11) NOT NULL COMMENT 'foreign key',
INDEX par_ind (customer_id),
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
KEY FK_EMAIL_CUSTOMER_idx (customer_id),
CONSTRAINT FK_EMAIL_CUSTOMER FOREIGN KEY (customer_id) REFERENCES customer (id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='email addresses';
Postman Complaint
{
"status": 400,
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"timeStamp": 1566840491483
}
Console Complaint
****email count 2
EmailAddress [id=1, type=1, email=bobby#bobby.com]
EmailAddress [id=2, type=1, email=bobby#gmail.com]
2019-08-28 17:33:07.625 WARN 8669 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000
2019-08-28 17:33:07.626 ERROR 8669 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'customer_id' cannot be null
2019-08-28 17:33:07.629 ERROR 8669 --- [nio-8080-exec-2] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2019-08-28 17:33:07.735 WARN 8669 --- [nio-8080-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement]
Therefore, with a post or put, I am not sure why the Spring Data JPA save does not satisfy the foreign key constraint for entities with oneToMany relationships. I am guessing it is either some missing annotations or something wrong with my sql script. Not sure why the update data does not persist to the email_address table. Does the emailAddress entity require some type of getter/setter for customer_id?
public class Customer extends Auditable<String> {
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer", cascade={CascadeType.ALL})
private List<EmailAddress> emailAddresses;
}
public class EmailAddress extends Auditable<String> {
#ManyToOne(fetch=FetchType.LAZY, cascade={CascadeType.ALL})
#JoinColumn(name="customer_id")
private Customer customer;
}
The mappedBy here means that the relationship between Customer and EmailAddress (i.e. the value of customer_id in customer table ) are determined by EmailAdress#cutomer but not Customer#emailAdresses.
What you are trying to show it just the content of Customer#emailAddress which will be ignored by Hibernate when deciding which DB values to be updated/inserted for this relationship. So you have to make sure EmailAddress#customer are set correctly.
For example , you can have the following method to add an email address to a Customer
public class Customer {
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer", cascade={CascadeType.ALL})
private List<EmailAddress> emailAddresses;
public void addEmailAddress(EmailAddress email){
//As said Hibernate will ignore it when persist this relationship.
//Add it mainly for the consistency of this relationship for both side in the Java instance
this.emailAddresses.add(email);
email.setCustomer(this);
}
}
And always call addEmailAddress() to add an email for a customer. You can apply the same idea for updating an email address for a customer.
I am trying to sort the rows in my table by the latest date first.
var userParkingHistory = from j in dataGateway.SelectAll() select j ;
userParkingHistory = userParkingHistory.Where(ParkingHistory => ParkingHistory.username == User.Identity.Name);
return View(userParkingHistory);
I can currently display the rows sorted by the username but I also want it to sort by the latest date first.
In my gateway, this is how I select the list:
public IEnumerable<T> SelectAll()
{
return data.ToList();
}
Where and How do I sort the data according to the latest date first ?
This is how I define my table:
CREATE TABLE [dbo].[ParkingHistory] (
[parkingHistoryId] INT IDENTITY (1, 1) NOT NULL,
[carparkId] INT NULL,
[username] VARCHAR (255) NULL,
[date] DATETIME NULL,
[description] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([parkingHistoryId] ASC)
);
Linq has orderby:
var userParkingHistory = from j orderby j.date in dataGateway.SelectAll() select j ;
Alsi, List has various extension methods to sort itself.
Try this:
var userParkingHistory = dataGateway.SelectAll().Where(p => p.username == User.Identity.Name).OrderBy(p => p.date).ToList();
return View(userParkingHistory);
I'm new in typo3 CMS and I'm now creating a new extension but I always get the following error when I try to execute query from repository.
1247602160: Table 'hr.tx_hr_domain_model_job' doesn't exist
this is my controller
<?php
namespace Hr\Hr\Controller;
class HrController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
protected $jobsRepository;
protected $objectManager;
public function initializeAction()
{
parent::initializeAction();
$this->objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$this->jobsRepository = $this->objectManager->get('Hr\\Hr\\Domain\\Repository\\JobRepository');
}
/**
* jobs list
*
* #return void
*/
public function listAction()
{
$this->view->assign('jobs', $this->jobsRepository->findAll());
}
}
and this is job repository class
<?php
namespace Hr\Hr\Domain\Repository;
class JobRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
}
this is the content of ext_tables.sql file
#
# Table structure for table 'tx_hr_job'
#
CREATE TABLE IF NOT EXISTS `tx_hr_job` (
`JobId` int(10) NOT NULL,
`Kunde` varchar(255) NOT NULL,
`Titel` varchar(255) NOT NULL,
`Ort` varchar(255) NOT NULL,
`Volltext` text NOT NULL,
`Bundesland` varchar(255) NOT NULL,
`Region` varchar(255) NOT NULL,
`Branche` varchar(255) NOT NULL,
`Berufsgruppe` varchar(255) NOT NULL,
`Stellenart` varchar(255) NOT NULL,
`Datum` date NOT NULL,
PRIMARY KEY (`JobId`)
);
any help?
By convention the table name should be tx_hr_domain_model_job, alternatively you can use table mapping, but it could be tricky.
Use the extension_builder for kickstarting your ext - it's great tool for creating basic models, you can do it just with drag'n'drop - also relations, etc.
What's more important it will create all required pieces of code, models, repositories TCA configs etc so you'll see what's the most valid approach.
In the documentation exactly says that associated data can be saved like:
use App\Model\Entity\Article;
use App\Model\Entity\User;
$article = new Article(['title' => 'First post']);
$article->user = new User(['id' => 1, 'username' => 'mark']);
$articles = TableRegistry::get('Articles');
$articles->save($article);
I tried this in my code but I get error:
Fatal Error
Error: Class 'App\Controller\TableRegistry' not found
File /Users/mtkocak/Sites/gscrm/src/Controller/BusinessesController.php
Line: 62
Here is my controller code. I am doubt that above code is valid for entity models.
public function add() {
$business = $this->Businesses->newEntity($this->request->data);
$record = new Record($this->request->data['Records']);
$address = new Address($this->request->data['Addresses']);
$telephone = new Telephone($this->request->data['Telephones']);
$email = new Email($this->request->data['Emails']);
$record->business = $business;
$record->address = $address;
$record->email = $email;
if ($this->request->is('post')) {
var_dump($this->request->data['Records']);
$records = TableRegistry::get('Records');
$records->save($record);
// if ($this->Businesses->save($business)) {
// $this->Flash->success('The business has been saved.');
// return $this->redirect(['action' => 'index']);
// } else {
// $this->Flash->error('The business could not be saved. Please, try again.');
// }
}
$telephonetypes = $this->Businesses->Records->Telephones->Telephonetypes->find('list');
$records = $this->Businesses->Records->find('list');
$businesstypes = $this->Businesses->Businesstypes->find('list');
$this->set(compact('telephonetypes','business', 'records', 'businesstypes'));
}
Here is my sql dump of table:
CREATE TABLE IF NOT EXISTS `businesses` (
`id` int(10) unsigned NOT NULL,
`record_id` int(10) unsigned DEFAULT NULL,
`businesstype_id` int(10) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=1 ;
ALTER TABLE `businesses`
ADD PRIMARY KEY (`id`), ADD KEY `FK_businesses_records` (`record_id`), ADD KEY `FK_businesses_businesstypes` (`businesstype_id`);
Any help is appreciated.
You are missing a use statement. All these examples in the book take for granted that you've started reading the tables section from the beginning and make use of:
http://book.cakephp.org/3.0/en/orm/table-objects.html#getting-instances-of-a-table-class
use Cake\ORM\TableRegistry;
ps. you don't have to build the entities manually when following the naming conventions
http://book.cakephp.org/3.0/en/orm/table-objects.html#converting-request-data-into-entities
http://book.cakephp.org/3.0/en/views/helpers/form.html#field-naming-conventions
http://book.cakephp.org/3.0/en/orm/table-objects.html#avoiding-property-mass-assignment-attacks