I don't know how to specify the title for the question, and that's why i cannot find the answer by my own.
I'll try to explain what I mean.
We have a database. Then, on the list of the databases there's something like category? it's unclickable and it's bold. It contains three databases preceded by underscore and each of this databases contains tables.
It looks something like:
Category
> _something1
table1, table2, table3...
> _something2
table1, table2, table3...
> _something3
table1, table2, table3...
How it's called and how can I reach the effect above?
Here, "Category" is a prefix for database names. So your databases names are
category_something1
category_something2
category_something3
They are displayed in a collapsible/expandable tree.
From what i understood from the question, You want to write a program that will show 6 rows like this:
Category: -Something 1 table1,table2,table3
-Something 2 table1,table2,table3 -Something 3 table1,table2,table3
First of all you would need to form the rows in ASC order.
Change some thing like this :
Array(Category,
Category_something1,
Category_something2_table1,
Category_something2_table2,
Category_something2_table3,
Category_something2,
Category_something3_table1,
Category_something3_table2,
Category_something3_table3,
Category_something3,
Category_something1_table1,
Category_something1_table2,
Category_something1_table3,)
into :
Array(Category,
Category_something1,
Category_something1_table1,
Category_something1_table2,
Category_something1_table3,
Category_something2,
Category_something2_table1,
Category_something2_table2,
Category_something2_table3,
Category_something3,
Category_something3_table1,
Category_something3_table2,
Category_something3_table3,)
Then Run a loop that splits each string into 3. if second value/third is not present print as heading/category else print as item/something.
While(ArrayKey is not equal to count(Array))
{
SplitString(ArrayCurValue,"_",$VarValue1,$VarValue2,$VarValue3); //split current string into 3 vars where _ is present
if($VarValue2 == "")
{
Print "<b>",$VarValue1,"</b>";
}else{
if($VarValue3 == "")
{
Print " -",$VarValue2;
}else{
Print " -",$VarValue3;
}
}
}
Related
I have model Product with name and category
On seed:
Product.create(name: "apple", category: "food")
Product.create(name: "biogesic", category: "medicine")
And a 2 dimensional array:
[[1, "tray of apple", 150.00], [1, "box of ballpen", 70.30]]
What I need is to get if the string inside the array contains or is on the table/database Product
Here's what I'm thinking but I'm lost:
isProduct = Product.where("name like ?", "%an apple%").first
Where "%apple%" is supposed to be the string on array, but with that code it is limited for 1 word only.
I don't need the product id, I just need it if it is on the Product table.
In a certain way, this can be accomplished with the Regular Expression Operator ~ for PostgreSQL and/or REGEXP for MySQL:
regex = array.flat_map { |_, sentence, _| sentence.split }.join('|')
Product.exists?(['name ~ ?', regex])
Product.exists?(['name REGEXP ?', regex])
Which produces:
SELECT 1 AS one FROM "products" WHERE (name ~ 'tray|of|apple|box|of|ballpen') LIMIT $1 [["LIMIT", 1]]
As it searches for the presence of every single word within the sentences tray of apple and/or box of ballpen.
So, in case you have a record like:
Product.new(name: 'tray of apple and box of ballpen')
It'll cover the query and return true.
How to add condition dynamically to sql query
for example if i have one element than it will look like
query=['one_element']
User.where('name LIKE ?, %"#{query[0]}"%')
but if it more than one
User.where('name LIKE ? and LIKE ? and Like... , %"#{query}"%', ..so on)
Im use myslq
so my main goal to split search query if it contains more than 2 words and search by them separately in one sql query
not where(name:'john dou') but where(name:'john' and name:'dou')
If you have a version of MySQL that supports RLIKE or REGEXP_LIKE:
User.where("RLIKE(name, :name_query)", name_query: query.join("|"))
Otherwise, you'll have to manually build with the ActiveRecord or operator:
# In the User model
scope :name_like, ->(name_part) {
return self.all if name_part.blank?
where("name LIKE :name_query", name_query: "%#{name_part}%")
}
scope :names_like, ->(names) {
relation = User.name_like(names.shift)
names.each { |name| relation = relation.or(name_like(name)) }
relation
}
Then you can pass it an array of any name partials you want:
query = ["john", "dou"]
User.names_like(query)
First split the word by it's separator like this query.split(' ') this will give you array of words. Then you can use like below in rails.
User.where(name: ['John', 'dou']
Suppose we have table person and table phoneand the relation between them is one to many.
I need to retrieve this like result with one query.
[
{
name:"abc",
lname:"def",
phones:[
{
dial_code="+1",
number:"12345667"
},
{
dial_code="+1",
number:"12345667"
}
]
},
{
name:"xyz",
lname:"lmn",
phones[
{
dial_code="+2",
number:"2643525"
}
]
},
{...}
]
I can do this by multiple query like first getting all persons and then get their phones one by one but i think its so weird and need lots of time and reduce performance. and if i get all data by joining table it wouldn't be like this JSON format.
Any idea will be appreciated.
Sorry for my bad English.
First things first, you cannot retrieve the desired result with multiple phone inside each person with one single query.
Now, running the query inside person loop will hugely affect the performance of the script if there are a lot of data. In this way, first, you need to execute a query to fetch all persons(say n persons). Then you have to again loop all n persons to fetch their respective phones.
So you need to run something like following inside $persons loop n times:
SELECT * FROM phone WHERE person_id = [$person_id]
Therefore in this way you need to execute n+1 queries.
To overcome this n+1 query problem we can apply a methodology which is called as eager loading. Here you also need to execute the first query to retrieve all persons and then write a query to fetch all phones which belongs to those retrieved persons:
SELECT * FROM person
Result($persons):
id name
5 John
10 Bob
20 Jenna
SELECT * FROM phone WHERE person_id IN (5,10,20)
Result($phones):
id person_id dial_code number
1 5 +2 12345
2 10 +1 12312
3 20 +1 98765
Now we combine these two results in PHP scripts to produce the desired array. In this way, we write only two queries instead of n+1 queries.
You can write a PHP script like following to combine the two result sets:
// Create an array of phones with person_id as key
$phones_with_person_id_as_key = [];
foreach($phones as $key => $phone) {
$phones_with_person_id_as_key[$phone->person_id][$key] = $phone;
}
// Loop $persons array and add phones to person object
foreach($persons as $key => $person) {
// create phones key and add data
if (!empty($phones_with_person_id_as_key[$person->id])) {
$person->phones = $phones_with_person_id_as_key[$person->id];
}
else {
$person->phones = [];
}
}
Now $persons contains the formatted desired output.
I'm trying to query a MySQL database for items coming from a textarea. My controller's store() function has the following code:
// [...] validation is done here and assumed ok
foreach(explode("\n", Input::get('itemlist')) as $line) {
$item = preg_split('/(?<=\d) (?=[a-z])|(?<=[a-z])(?=\d)/i', $line);
if (isset($item[1])) {
echo 'Looking for ' . $item[1];
$itemObj = DB::table('items')->select('name', 'id')->where('name', '=', trim($item[1], "\r"))->first();
var_dump($itemObj);
}
}
The data received from Input::get('itemlist') is a list of items and amount, something like:
5 apples
2 oranges
1 banana
The Looking for ... part displays the item names properly. Also, the var_dump will actually show the proper result for the last thing searched for, everything else is just 'null'.
Is there something about DB:table that stops from doing queries in a loop like this? Should I do this some other way? Thanks!
EDIT Turns out there were trailing '\r' after each line except the last one so the query was for "Some Item\r" and not "Some Item". Fixed it above!
I have collection of numbers like: 11111, 12345, 12346 stored in a list in c# code. I need to compare this list against sql database column of numbers similar to this and find out if matching numbers exist. Below is what i am doing:
foreach (number in numbers)
{
//get column data through sql reader and iterate through it:
foreach(column in columnData)
{
if(number == column)
{
// do something
}
}
my question is this right approach? Or is there a better way to do this? As it looks like this requires lots of processing.
I would so something like this..
var matches = columnData.Where(z=> numbers.Contains(z=>z.columnData)).ToList();
or
var matches = columnData.Select(z=> z.columnData).Intersect(numbers);