I know that we can get sql query from magento model collection using this,
getSelect();
But I can get query from only the model collections, not worked in others or May be I dont know how to use it.
Here I want to know what query is running behind this,
$productModel = Mage::getModel('catalog/product')->getCollection();
$attr = $productModel->getResource()->getAttribute("color");
if ($attr->usesSource()) {
echo $color_label = $attr->getSource()->getOptionText("28");
}
If I use this,
echo $productModel->getSelect(); exit;
I'm just get the one part the query only, like,
SELECT `e`.* FROM `catalog_product_entity` AS `e`
Update:
This is my full code,
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$productModel = Mage::getModel('catalog/product')->getCollection();
$attr = $productModel->getResource()->getAttribute("color");
if ($attr->usesSource()) {
$color_label = $attr->getSource()->getOptionText("28");
}
$productModel->printlogquery(true);exit;
Please help me guys,
Your order condition is not visible in the query. The reason your order isn't showing is because the orders are added to the query during the load() method.
See Varien_Data_Collection_Db::load()
Try calling load(true) to see the complete SQL containing the order by clause.
$productModel->load(true);
$productModel->printLogQuery(true);
Hope it helps.
If you want to see what is the exact query, then you can get this by using:
$productModel->printlogquery(true);exit;
Use this code after you have loaded your model's object and applied all conditions.
I hope this will help you.
Magento collecting data with lot of internal queries - models and lot of checks, and may be more than 1 table. So it is not possible to get the query like what I'm looking for.
Related
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.
So i have this code wish is supposed to retrieve me some view for a web service.
$records = Publication::all();
if(isset($headers["input"]["from"])) {
$from = Carbon::createFromFormat('Y-m-d', $headers["input"]["from"])->toDateTimeString();
$records = $records->where("created_at", ">", $from);
}
if(isset($headers["input"]["until"])) {
$until = Carbon::createFromFormat('Y-m-d', $headers["input"]["until"])->toDateTimeString();
$records = $records->where("created_at", "<", $until);
}
This should return me some publications when passing a GET argument of 2015-07-21 already... But it returns nothing. I tried testing to see what was going on doing a dd($results) after the code but i got nothing on any way i have tried. I tried passing ->get() and ->all() and still got nothing. I even tried calling only the method and not assign to the same $record variable although it did not make sense to me i was all in about fixing this.
Maybe is a problem with Sql Statement? Comparing dates? Carbon variables look fine when dd($until) or dd($from)
EDIT: Since i needed this to work i explored other ways... What i did was transform Publication::all() to Publication::query() ( this will get you QueryBuilder ) Then i worked with Query Builder ->where(field,comparison,value) and then finally retrieved the result with $records->get(); That Way you will still get the Model Collection because if you use DB::table('publications') and then the same code when you do ->get() you will only get the array of elements and no relationship loading like in model. Hope i made my point and explained well. And sorry if i did not. I really tried my best. This is now SOLVED!
Since i needed this to work i explored other ways... What i did was transform Publication::all() to Publication::query() ( this will get you QueryBuilder ) Then i worked with Query Builder ->where(field,comparison,value) and then finally retrieved the result with $records->get(); That Way you will still get the Model Collection because if you use DB::table('publications') and then the same code when you do ->get() you will only get the array of elements and no relationship loading like in model. Hope i made my point and explained well. And sorry if i did not. I really tried my best. This is now SOLVED!
When working on Laravel, we do query like this:
$user = DB::table('users')->where('name', 'John')->first();
How can I view the generated sql query? This is something very important for debugging during the development.
Thank you.
According to this answer, you should be able to use this to get the last executed query :
$queries = DB::getQueryLog(); // gets a log of all executed queries
$last_query = end($queries); // gets the last one
You can also add this snippet:
Event::listen('illuminate.query', function($sql)
{
var_dump($sql);
});
It will output all queries being executed in your request.
Not a direct answer as other people have answered this but take a look at this composer package, it is very helpful and displays all of your queries and more.
https://github.com/barryvdh/laravel-debugbar
Using CI for the first time and i'm smashing my head with this seemingly simple issue. My query wont insert the record.
In an attempt to debug a possible problem, the insert code has been simplified but i'm still getting no joy.
Essentially, i'm using;
$data = array('post_post' => $this->input->post('ask_question'));
$this->db->insert('posts', $data);
I'm getting no errors (although that possibly due to disabling them in config/database.php due to another CI related trauma :-$ )
Ive used
echo print $this->db->last_query();
to get the generated query, shown as below:
INSERT INTO `posts` (`post_post`) VALUES ('some text')
I have pasted this query into phpMyAdmin, it inserts no problem. Ive even tried using $this->db->query() to run the outputted query above 'manually' but again, the record will not insert.
The scheme of the DB table 'posts' is simply two columns, post_id & post_post.
Please, any pointers on whats going on here would be greatly appreciated...thanks
OK..Solved, after much a messing with CI.
Got it to work by setting persistant connection to false.
$db['default']['pconnect'] = FALSE;
sigh
Things generally look ok, everything you have said suggests that it should work. My first instinct would be to check that what you're inserting is compatible with your SQL field.
Just a cool CI feature; I'd suggest you take a look at the CI Database Transaction class. Transactions allow you to wrap your query/queries inside a transaction, which can be rolled back on failure, and can also make error handling easier:
$this->db->trans_start();
$this->db->query('INSERT INTO posts ...etc ');
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
// generate an error... or use the log_message() function to log your error
}
Alternatively, one thing you can do is put your Insert SQL statement into $this->db->query(your_query_here), instead of calling insert. There is a CI Query feature called Query Binding which will also auto-escape your passed data array.
Let me know how it goes, and hope this helps!
Forgive me for re-wording and re-asking this question, but the answers I received a couple weeks back didn't help much...
Basically, I'm looking to somehow combine multiple database queries in Wordpress to retrieve user IDs by searching for term in the 'usermeta' table, but only entries that have a certain 'meta_value'
I'm trying to combine:
$users = $wpdb->get_results("SELECT user_id, meta_value as 'business_name'
FROM $wpdb->usermeta
WHERE meta_key = 'business_name'");
AND:
$users = $wpdb->get_results("SELECT user_id, meta_value as 'business_description'
FROM $wpdb->usermeta
WHERE meta_key = 'business_description'");
To essentially have this:
$users = $wpdb->get_results("SELECT user_id, business_name, business_description
FROM
WHERE
business_name LIKE '%{$keyword}%' OR
business_description LIKE '%{$keyword}%'");
I've looked into INNER JOINs and subqueries, but cannot seem to find a good solution. I realize that I can get away with multiple queries, but this would be searching through possibly thousands of entries, so I'd like to optimize it as much as possible.
Hi #John:
If I understand your question correct (since you gave a technical example of what you were attempting but not a description of what end result you were trying to accomplish I'm not sure) it seems you are doing a user search? If yes, below is what I think you need.
<?php
// Load WordPress, but only for standalone example use
include '../wp-load.php';
// Make sure the database object is available
global $wpdb;
// Get value entered by the user
$keyword = $_GET['keyword'];
// This would be used in your code; the percent would confuse prepare() below
$keyword = "%{$keyword}%";
// Join each meta field as a separate join and reference the meta_key in the join
// prepare() below replaces "%s" with a quoted string value
$sql =<<<SQL
SELECT
users.user_nicename AS user_name,
bizname.meta_value AS business_name,
bizdesc.meta_value AS business_description
FROM
{$wpdb->users} AS users
INNER JOIN {$wpdb->usermeta} AS bizname
ON bizname.user_id=users.ID
AND bizname.meta_key='business_name'
INNER JOIN {$wpdb->usermeta} AS bizdesc
ON bizdesc.user_id=users.ID
AND bizdesc.meta_key='business_description'
WHERE 1=0
OR bizname.meta_value LIKE %s
OR bizdesc.meta_value LIKE %s
SQL;
// User prepare() to avoid SQL injection hacks
$sql = $wpdb->prepare($sql,$keyword,$keyword);
// Finally, get yer results!
$users = $wpdb->get_results($sql);
echo "<ul>";
foreach($users as $user) {
echo "<li>User= {$user->user_name}, Business= {$user->business_name}:{$user->business_description}</li>";
}
echo "<ul>";
The above is a complete working example you can copy to a file in the root of your website and call it something like /test.php allowing you to see it work by using a URL like this:
http://example.com/test.php?keyword=Accounting
Of course, this may be less performant at times than using multiple queries because of the query caching systems built-in to WordPress but it's impossible to tell without some benchmarking.
Hope this helps.
-Mike
P.S. By the way, I'm assuming you were not aware of it but since your prior question evidently hadn't gotten much WordPress love nor had this one I'll mention the WordPress Answers website which is a sister site to StackOverflow. Lots of WordPress enthusiasts are on hand over there to answer WordPress-specific questions.My experience with StackOverflow is they have some of the best developers on the web but few here have specific experience developing with WordPress so you end up with people here trying to answer MySQL questions without knowing the WordPress database schema and without knowing WordPress-specific best practices. Ask over at WordPress Answers and I think you'll an improved quality of answers to your WordPress-specific questions.
Can you post some details on the error messages you are receiving? The SQL here looks ok, but it's impossible to tell what the problem is without seeing the error messages.
For example, are you sure the $keyword field is being populated? How many results to return? Have you tried it without the WHERE statement or just a single OR to troubleshoot? Also, have you tried running this SQL directly on your server with some test keywords?
Give us more of an idea on what you have tried to fix the problem and we'll be able to assist further.
Kind Regards
Luke Peterson