Laravel Query Builder join on json data column - mysql

On my database, I have a notifications table that has a data column containing a JSON string like this one:
{"sender_id":2,"sender_name":"John Doe","message":"Hello world!"}
What I need is to join the users table on users.id = notifications.data.sender_id but I don't know how or if it's even possible. Couldn't find any info regarding this kind of query.
Looking forward to reading your solutions. Thanks!

You could do a little hacky solution which is this:
$id = 123;
YourModel::where('json_data_column', 'like', '%"sender_id":' . $id . ',%');
You are basically doing a string search in the JSON. However, there is also a JSON column type in MySQL, which allows better support for JSON searches. You can then do:
$id = 123;
YourModel::where('json_data_column->sender_id', $id);

Related

How to retrieve data from json column using codeigniter?

I’m a beginner with codeigniter. I’m trying to retrieve data from json column of my sql db
The db structure is like this
DB NAME : order
——————————————————------------------------------------------
Id | description
——————————————————————————————————---------------------------
1 | {“pc”: [{ “brand”: “name”}], “mouse”: [“LL”, “DC”]}
————————————————————————————————————--------------------------
For example, I want to retrieve all instances that has mouse = dc
$data = $this->db->select($select)->from(‘order’)
->where(“mouse”, “DC”) ->get()->result();
Well, I've never worked like this before, but with the help of the user ascsoftw answer, I've found this section on the MySQL documentation that might help, I think this is even better for you case.
Then, your query may look something like this (sorry if I'm mistaken, like I said, never worked like this before):
SELECT Id FROM order where description->>"$[1][1]";
From what I understand that would retrieve all the Id's of the mouse (array index 1) with DC's description (array index 1 as well).
You may keep reading the docs of MySQL if that didn't help.
By the way,is worth mention that, you have several ways to do queries in CodeIgniter, if the CI query builders does not adapt to what you want to do, you can always do as the following example:
$query = "SELECT * FROM table_name";
$result = $this->db->query($query);
if($result->num_rows() != 0)
{
foreach($result->result() as $row)
{
return something
}
}
else
{
return false
}
Let me know if that helped you so I can edit with the correct answer for anyone running into the same problem.

how to deal query that mysql json data type as condition with spring-data-jpa

With mysql, there is a column used json data type. i want to execute query with the column as condition. With Sql, i can write it like bellow.
select * from user where json_extract(address,'$.city')= 'beijing'
But using spring-data-jpa, i don't know how to implement it. JPQL have no provided some api implement json_extract. And the JpaSpecificationExecutor of jpa have not provide same function too. If someone know how to do it, please answer this question.
Try this:
#Query(value = "select * from user where json_extract(address,'$.city') = '?city'", nativeQuery = true)
List<User> findUsersByCity(String city);
I didn't check it.
Good luck

Select querybuilder for cassandra

I'm trying to get a few columns from cassandra table with just one column as Json string using datastax queryBuilder. I tried to construct the query in folloing ways and didnt work.
Select.Where selectByKey = QueryBuilder.select().fcall("fromJson", "columnX")
.column("columnX")
.from("keyspaceName", "tableName")
.where(QueryBuilder.eq(key, QueryBuilder.bindMarker()));
Select.Where selectByKey = QueryBuilder.select().fcall("fromJson", "columnX")
.all()
.from("keyspaceName", "tableName")
.where(QueryBuilder.eq(key, QueryBuilder.bindMarker()));
Select.Where selectByKey = QueryBuilder.select().fcall("fromJson", "columnX")
.column("[json]")
.from("keyspaceName", "tableName")
.where(QueryBuilder.eq(key, QueryBuilder.bindMarker()));
Errors are like, no viable alternative at input 'columnX' (SELECT "[json]",fromJson[(]'columnX...)
All the columns are basically text except columnX which has a text in a Json format. I need some solution to get a single column as json, or whole record as json using Query Builder. Thanks
From what I understand from here, you need to use, QueryBuilder.column("columnX") instead of "columnX" as a parameter to fcall.
Hope it helps!

Database - getting multi dimensional data

Is there some command in mysql or nosql databases so i could get data sorted in multidimensional array by some sort field?
For example : SELECT * FROM TABLE ARRAYSORT field1
so we would get
array('field1_value1'=>array(data),'field1_value2'=>array(data))
or we must process data in our programming language to get array like this.
It is just imposible that no database support query like this.
I don't know if that's what you want to do:
PHP:
$result = $polaczenie->query($sql)
while ($row = $result->fetch_array()){
$array[$Row['firstColumnToSort']][$Row['secondColumnToSort']]=data;
}
Or something like that

Using enum in drupal

I have a mysql table id,name,gender,age religion( enum('HIN','CHR','MUS') ,category(enum('IND','AMR','SPA') where last 2 are enum datatype and my code in drupal was
$sql="SELECT * FROM {emp} WHERE age=".$age." and religion=".$rel." and category=".$categ;
$result=db_query_range($sql,0,10);
while($data=db_fetch_object($result))
{
print $data->id." ".$data->name."<br>";
}
I get no result or error . I'm trying different query with each field and all are fine except using enum.
for ex: $sql='SELECT * FROM {emp} WHERE religion="'.$rel.'"';
Is there any problem in using enum datatype in drupal
Enum is not something that I believe drupal can make with the schema API, which is what you in most cases want to use for modules and stuff. Also you are lacking an ending ) in your reference to it, but I'm sure you did it right when your made the table.
Enum is only a constraint that is built into the database when inserting values. So if you try to insert an invalid value, you will insert an empty string instead. So it wont have any effect on Drupal querying to get data. It also wont have any effect when Drupal insert values, other than converting invalid values to empty strings. You might want to check the your data, to see if it is as expected. You might just get no results because your query doesn't match anything.
Another thing is the way you construct your queries is a big NO NO, as it's very insecure. What you should do is this:
db_query("SELECT ... '%s' ...", $var);
Drupal will replace %s with your var and make sure there is no SQL injection and other nasty things. %s indicates the var is a string, use %d for ints and there are a few others I can't remember just now. You can have several placeholders like this, and they will be insert in order, much like the t function.
Seconding Googletorps advise on using parameterized queries (+1). That would not only be more secure, but also make it easier to spot the errors ;)
Your original query misses some quotes around your (String) comparison values. The following should work (Note the added single quotes):
$sql = "SELECT * FROM {emp} WHERE age='" . $age . "' and religion='" . $rel . "' and category='" . $categ . "'";
The right way to do it would be something like this:
$sql = "SELECT * FROM {emp} WHERE age='%s' and religion='%s' and category='%s'";
$args = array($age, $rel, $categ);
$result = db_query_range($sql, $args ,0 , 10);
// ...