Add column in a relational table - Symfony - sql

I'm learning how to use Symfony and I have a logical issue.
Here is what I want to do :
I have two entities: post and category.
Between them, I have a ManyToMany relationship.
Here, everything works as I expected. I have two forms and a relational table between the entities named: post_category
I'd like to give a range for each post which is in a category.
So I thought that I have to insert the third column in my relational table.
But here I'm lost.
How can I create this?
Should I do it manually and create a custom query in a repository?
I never used a custom query yet, so if someone can give some clues to do it...
Thanks a lot!
Here are my (simplified) entities:
class Category
{
private $id;
private $title;
private $description;
private $relPosts;
}
class Post
{
private $id;
private $title;
private $content;
private $slug;
private $relCategories;
private $range;
private $createdAt;
}
My conditional table "post_contenu":
post_id | contenu_id

Related

Filter on relationship's field

I'm trying to fetch all entities for a given relationship's field match (I want my entity's relationships filled out in the result). Trying with Filter on session.loadAll() to filter on the relationship's field but I can't make it work.
My entities definition looks like:
#NodeEntity
class ClockAction {
#Id #GeneratedValue
private Long id;
private String description
private User user;
private Office office;
}
#NodeEntity
class User {
#Id #GeneratedValue
private Long id;
private String name;
private List<ClockAction> clockActions;
}
#NodeEntity
class Office {
#Id #GeneratedValue
private Long id;
private String name;
private List<ClockAction> clockActions;
}
From that I'm need to retrieve all ClockAction entities where User.id is in a given set of Ids.
Here is my try :
Filter filter = Filter("id", ComparisonOperator.IN, userIds);
filter.setNestedPropertyName("user");
filter.setNestedPropertyType(User.class);
filter.setNestedRelationshipEntity(true);
return session.loadAll(ClockAction.class, filter);
This always returns an empty result. Any idea of what I'm doing wrong?
Using a session.query like this
session.query(ClockAction.class, "MATCH p=(a:ClockAction)-[r]-() WHERE id(r) IN {ids} RETURN nodes(p), rels(p), a, r ORDER BY a.id", params)
works but only office field of ClockAction gets filled out on the result entity, user is always null...
Any help is appreciated :)
Some things first:
It is unfortunately currently not possible to filter for an id field because the filters only work with properties. Id fields are queried in cypher with the id function. (id(n) != n.id)
You are not looking for a relationship entity (remove filter.setNestedRelationshipEntity(true);)
Now you have the choices:
Query for another property of the User class with the filter.
Alter your cypher query with something like this: "MATCH p=(a:ClockAction)-[r]-(n) WHERE id(n) IN {ids} RETURN nodes(p), rels(p), a, r ORDER BY a.id" The changes are based on the assumption that the code snippets are correct and User is not a relationship.
Additional information (edit):
If no relationship is defined, Neo4j OGM will create them directed outgoing from the node you are saving. Your graph could look like this (ClockAction as root):
Or like this (User as root with multiple ClockActions):
You are not getting the Office because your current query path is (:User)-[r]-(:ClockAction) there is no information in the path about an Office.
MATCH (n:User)-[ur:CLOCK_ACTIONS]->(c:ClockAction)-[or:OFFICE]->(o:Office) WHERE id(n) IN {ids} RETURN c, n, ur, o, or is a pretty straight forward query you could use. It removes the path centric style but also loads all the data you need.
If the graph was stored through the User but this is just an example and can be applied however the data looks in your graph, you won't see any User information on the ClockActions because as it saves without any hint Neo4j OGM will also expect the data related in a outgoing direction from the class you want to load.
Now it is necessary, keeping the User example, to add a #Relationship(type="CLOCK_ACTION", direction = "INCOMING") to the user field in your ClockAction class.
This will give Neo4j OGM the needed hint to put the User data it has in your user field.
I ended up following advises from #meistermeier and annotate my relationships giving direction.
Below is my model entities :
#NodeEntity
class ClockAction {
#Id #GeneratedValue
private Long id;
private String description
#Relationship(direction = Relationship.OUTGOING)
private User user;
#Relationship(direction = Relationship.OUTGOING)
private Office office;
}
#NodeEntity
class User {
#Id #GeneratedValue
private Long id;
private String name;
#Relationship(direction = Relationship.INCOMING)
private List<ClockAction> clockActions;
}
#NodeEntity
class Office {
#Id #GeneratedValue
private Long id;
private String name;
#Relationship(direction = Relationship.INCOMING)
private List<ClockAction> clockActions;
}
What #meistermeier suggested for query did not work for me, but gave me inspiration and I found this working fine :
MATCH p((u:User)-[ur]-(c:ClockAction)-[or]-()) WHERE id(u) IN {ids} RETURN p, rels(p)

In which situations use public, protected, private (php oop)

I am learning php oop. But I can not understand in which situations use public, private and protected. I know that public is accessable inside the class and outside the class, protected inside the class and inside classes which inherites it, private is accessable only inside the class. But how to know that the property or method must be protected or private ? I know that if write class for connecting database they must be protected or private. But, an example: I am writing registrating class(is the code below true ?):
private $email;
private $username;
private $password;
private $securitycode;
private function register {
//here registrations codes, may be I must use public function ?
}
Another example: I have news section in the website and want to get news details (id, title, text, author) and write News class (is given code below true ?):
private $id;
private $title;
private $text;
private $author;
public function get_one_news($this->id) {
//here the code for getting the news, may be I must use protected function ?
}
Another example: I want to get number of users or news: Which I have to use : public, protected or private function ?
Another example: Every user(registered or unregistered) can add comment(id, comment): Can I use public $id; public $comment ? or I have to use protected or private ?
Please, I need your advices. Which(public, protected, private properties and functions) to use if I want to add/get news, to register/login user, to add/edit/get data from database tables, to make fileuploading and etc. ?
I could not find answers to my question.
You can think about it like this. The non-private parts of your class are its interface to the outside world. You can change the private inner workings as much as you want, without thinking about breaking other code in your system. However as soon as you start changing the non private parts you have to take into consideration all the users of your code depending on your current public interface. So I think as a general rule of thumb you should try to make your code as private as possible.By that you can greatly increase the encapsulation of your codebase, allowing you to change the internal implementation details without affecting the code using your class.
So in a first step think about what functionality your new class should offer its users. This should then become its public interface. Then think about whether or not your class should be inherited from and what parts should be allowed to be changed in its subclasses. Everything else should be private as it is the classes internal implementation.

Modeling a M-N Relationship in OOP

This is the closest thing I could find to my problem on here
I'm working on a projects and I want to add a security model to it, so since I have experience first hand how bad jumping into coding and skipping the planning phase is I decided to do that first. So I created an ERD, cool do it all the time, then the UML Class diagram, haven't done one of these since college, ok a little bit of google, go it.
See ERD And UML Class Diagram Here
The image above is an exert of what I have so far, I know that I certainly need a User Class and a Permission Class but I'm not sure how to handle the relationship between the two. I know generally in an M-N relationship you model it with a property that is a collection of the related class but what about the properties of the related class? Below is my best guess, if anyone has corrections, comments, or links to material to read that would be awesome. My goal is the proper implementation of OOP thanks in advance.
class User{
private $id;
private $password;
private $active;
private $permissions;
/* skip getters and setters */
function getUserPermissions(){
return UserPermission[];
}
}
class UserPermission{
private $id;
private $deny;
private $grant;
private $active;
/* skip getters and setters */
function getPermissions(){
return Permission[];
}
}
class Permission{
private $id;
private $name;
private $description;
private $active;
/* skip getters and setters */
}
You could have these arrays that you return directly, as arrays or lists. But that is not so important.
What is more important, every UserPermission, that is a class association, should have an array of User's and an array of Permission's.
Also, every User should have his UserPermission and every Permission should have its UserPermission, too.
And User should have no array for UserPermission's. Their association is 1:n, with n on the side of User. That means: UserPermission has many User's, User has 1 UserPermission.

Play Framework: JPA one-to-many relationship between three entities?

I am building a web application using the play framework and I am running into problems with creating the database model using this schema
**Client** – (many to many) – **Events**
\ /
(one to many) (one to many)
\ /
**COMMENTS**
I am able to create and add the relationships
Event event = new Event("Party");
Client client = new Client("test#gmail.com","fname","lname","street","phonenum");
Comment comment = new Comment("test comment!");
//Add relationships
client.addEvent(event);
event.addClient(client);
event.addComment(comment);
comment.addEvent(event);
event.addClient(client);
client.addComment(comment);
But when I try to persist the data
client.save();
event.save();
comment.save();
I receive the error
[error] Test CommentModelTest.testClientEventCommentRelationship failed:
javax.persistence.PersistenceException: org.h2.jdbc.JdbcSQLException: Unique index or primary
key violation: "PRIMARY_KEY_4A ON PUBLIC.EVENT_CLIENT(EVENT_ID, CLIENT_EMAIL)"; SQL statement:
[error] insert into event_client (client_email, event_id) values (?, ?) [23505-172]
The class definitions are shown below, I would really appreciate it if someone could help me solve this issue. Am I defining the relationship incorrectly? Thanks in advance!
Client Class:
#Entity
public class Client extends Model {
#Id
public String email;
#Required
public String firstName;
#Required
public String lastName;
public String homeAddress;
public String phoneNumber;
#ManyToMany(mappedBy="clients", cascade=CascadeType.ALL)
public List<Event> events = new ArrayList<Event>();
#OneToMany(mappedBy="client", cascade=CascadeType.ALL)
public List<Comment> comments = new ArrayList<Comment>();
Event Class:
#Entity
public class Event extends Model {
#Id
public Long id;
#Required
public String eventName;
#ManyToMany(cascade=CascadeType.ALL)
public List<Client> clients = new ArrayList<Client>();
#OneToMany(mappedBy="event", cascade=CascadeType.ALL)
public List<Comment> comments = new ArrayList<Comment>();
Comment Class:
#Entity
public class Comment extends Model {
#Id
public Long id;
#Required
public String message;
#ManyToOne(cascade=CascadeType.PERSIST)
public Client client;
#ManyToOne(cascade=CascadeType.PERSIST)
public Event event;
---Edit:-------------------------------
I realized where I went wrong. In case you are running into a similar error, check to see if you are using the models correctly! In my JUnit test I tried adding the same client to an event twice, causing the primary key (email) to be duplicated.
the corrected relationship code should be as follows:
client.addEvent(event);
event.addClient(client);
event.addComment(comment);
comment.addEvent(event);
comment.addClient(client);
client.addComment(comment);
The exception says that you are trying to add the same relationship twice.
"PRIMARY_KEY_4A ON PUBLIC.EVENT_CLIENT(EVENT_ID, CLIENT_EMAIL)"
I guess this is on the table between the events and the clients, so it maps the ManyToMany relationship.
client.addEvent(event);
HERE --> event.addClient(client);
event.addComment(comment);
comment.addEvent(event);
HERE --> event.addClient(client);
client.addComment(comment);
It's added twice and there is a unique index that prevents that.

DataNucleus JDO reverse datastore 1:1 mapping with foreign keys

I have a DataNucleus project and I am using JDO to reverse map a datastore to my classes. I do this very easily with:
package com.sample;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
#PersistenceCapable(table = "source")
public class Source {
#PrimaryKey
private String source_id;
private Topic topic_id;
private String url;
private String description;
// getters and setters
}
public class Topic {
private String topic_id;
private String topicName;
private String topicDescription;
// getters and setters
}
The topic_id is a foreign key to another table, topic, which contains an id, a topicName, and a topicDescription.
I know that it is possible, using annotations, to return topic.id, topic.topicName, and topic.topicDescription with the topic_id. I just cannot figure out how, and I find the documentation to be a bit cryptic, especially for reverse mapping.
Can anyone lend a hand and provide an example? I've tried playing around with the #ForeignKey and #Element annotations, but I haven't had any luck yet.
Thanks!
If the "topic_id" is a FK to another object (which isn't posted), then the Java class should have a Topic object field in there, like any normal 1-1 (Object-Oriented) relation