There is gallery on my site, and every picture has own tag. All of the tags are sorting chaotically. I want to sort them by value of field "index" in galleryTagsTable.
When it's show chaotically code was:
foreach ($_tags as $item) {
$select = new Select();
$tags[] = $this->getGalleryTagsTable()->fetchAll($select->where(array('id' => $item)));
}
To make sorting by field "index", I created this field and wrote this code:
foreach ($_tags as $item) {
$select = new Select();
$tags[] = $this->getGalleryTagsTable()->fetchAll($select->where(array('id' => $item))->order('index DESC'));
}
but it still doesn't work. I tried to write without 'DESC' & tried to sort by 'id'. None of these work.
Supposing that your Select() object is some kind of extended object of Zend_Db_Select, I think this is not working as you expected because that's not the correct syntax for the where clause. Correct one would be:
$select->where('id = ?', $item)
->order('index DESC');
Note the '?' wildcard on the expression. This is made in case you don't want it to be an equals but a greater than, or other comparison clauses such as RLIKE. And please, note also that it's not an array.
Probably your where clause wasn't working as intended and that was causing the problems on the order of your tags since they were not grouped by id.
I hope this helps.
Related
I would like to maintain a number of rules in a custom post type.
A rule will basically contain the expression part of an PHP IF construct, together with some output content.
In my plugin, I would like to loop through these rules, and for each rule use the rule in an IF expression, and then if true, do something with the associated output content.
I plan to store the rule expression as a text field, but how can I take this text field and use it in the IF expression?
I have tried to add the expression to a variable in PHP, and then use that variable as the expression. This doesnt seem to be working.
<?php
// Basic idea
// Wordpress query ($args not detailed in this example)
$rules = get_posts( $args );
// Example of post_meta field: tmbd_rule
// Post A -> tmbd_rule = '$varA == 2 && $varB > 17'
// Post B -> tmbd_rule = '$varA == 3 && $varB = 28'
foreach ($rules as $rule) {
$expression = $rule -> tmbd_rule;
if ($expression) {
// Do something clever
}
}
So - I am looking for this run through the list of rules and "do stuff" when a rule/condition is met :-)
You could use phps built-in eval() function in order to evaluate the result of your rules.
You can benefit from expression language it can be used without Symfony Framework as standalone library
https://symfony.com/doc/current/components/expression_language.html
For example(taken from docs):
class User
{
public $age;
}
$user = new User();
$user->age = 34;
$expressionLanguage->evaluate(
'user.age in 18..45',
[
'user' => $user,
]
); // true
I can see now two options for this, which is secure. One what #Robert proposed.
Second, you create 3 inputs, two select list and a text field.
1 select list will contain the variable name. ('variable')
1 select list will contain the operation. ('operation')
1 text field will contain the value which is desired. ('value')
Than you need to match and build 'together' the condition with ifs.
foreach ($rules as $rule) {
if ($rule->condition == '==' && $rule->variable == $rule->value || $rule->condition == '!=' && $rule->variable != $rule->value) {
// Do something clever
}
}
If you need more than one condition, than you need to group together and create a 4th field which says if it's or or and the connection between them. In this case the loop changes, like you check every condition separately, and than you looking for the second condition set (or/and) if it's fulfill your requirements according to your operation.
I'm trying to get this string of tags and iterate through it to get the respective tag's columns on another table:
1A-3,1-1,1-2,3-4,4-6,4-8,6-13,6-15,8-6,8-11,7A-4,7A-5,7A-6
Checks against:
$ministry = AgencyLogin::find(196);
$prefs = $ministry->Ministry_Preferences;
$tags = explode(',', $prefs);
foreach ($tags as $tag) {
$sub_categories[] = DB::table('descriptor')
->where('tag', $tag)
->select('subcategory', 'description')
->first();
}
//dd($sub_categories);
return view('agencydash', compact('sub_categories'));
dd($prefs) prints the correct string. $sub_categories[] never converts to an actual array, so can't be parsed like one, and my limited experience in Laravel means I don't know how to turn a query like this into an array instead the current thing it is, an object.
dd($sub_categories) after I treat it as an object prints a single result which seems to be random:
{#262 ▼
+"subcategory": "SUPPORT ROLE"
+"description": "Project Management"
}
I've been teaching myself Laravel and php steadily, so problems like this open more questions then I can answer yet.
Anybody know what I'm missing?
Why are you iterating through $tags and not using whereIn method and getting a whole collection of relevant rows?
$ministry = AgencyLogin::find(196);
$prefs = $ministry->Ministry_Preferences;
$tags = explode(',', $prefs);
$sub_categories = DB::table('descriptor')
->whereIn('tag', $tags)
->get(['subcategory', 'description']);
//dd($sub_categories);
return view('agencydash', compact('sub_categories'));
Docs
I am making a real estate related app and I've been having a hard time figuring out how to set up the query so that it would return "Only Apartments or Duplexes within selected areas" I'd like to user to be able to find multiple types of property in multiple selected quadrants of the city.
I have a database with a column "type" which is either "Apartment", "House", "Duplex", "Mobile"
In another column I have quadrant_main with values: "NW", "SW", "NE", "SE".
My code works when there is only 1 quadrant selected, but when I select multiple quadrants, I seem to get results which includes ALL the property types from the second or third or 4th quadrant, instead of only "Apartment" and "Duplex" or whatever types the user selects... Any help will be appreciated! thx in advance.
My controller function looks like this:
public function quadrants()
{
$input = \Request::all();
$currentPage = null;
$column = "price";
$order = "desc";
//
// Looks like the input is like 0 => { key: value } ...
// (an Array of key/value pairs)
$q = Listing::where('status','=','Active')->where(function($query) {
$input = \Request::all();
$currentPage = null;
$typeCount = 0;
$quadrantCount = 0;
foreach( $input as $index => $object ) {
$tempObj = json_decode($object);
$key = key((array)$tempObj);
$val = current((array)$tempObj);
if ( $key == "type" ) {
if ( $typeCount > 0 ) {
$query->orWhere('type', '=', $val );
}
else {
$query->where('type', '=', $val );
$typeCount++;
}
}
if ( $key == "quadrant_main" ) {
if ( $quadrantCount > 0 ) {
$query->orWhere('quadrant_main', '=', $val );
}
else {
$query->where('quadrant_main', '=', $val );
$quadrantCount++;
}
}
// else {
// $query->orWhere($key,$val);
// }
}
if( $currentPage ) {
//Force Current Page to Page of Val
Paginator::currentPageResolver(function() use ($currentPage) {
return $currentPage;
});
}
});
$listings = $q->paginate(10);
return $listings;
Looking at your question, its a bit confusing and not much is given to answer definitely. Probable causes of your troubles may be bad data in database, or maybe corrupted input by user.
Disclaimer: Please note that chances are my answer will not work for you at all.
In that case please provide more information and we will work things
out.
There is one thing that I think you have overlooked and thus you are getting awry results. First let me assume a few things.
I think a sample user input should look like this:
array(
0: '{type: Apartment}',
1: '{type: Duplex}',
2: '{quadrant_main: NW}',
3: '{quadrant_main: SW}',
)
What the user meant was give me any apartment or duplex which belongs in NW or SW region.
So after your loop is over, the final SQL statement should be something like this:
Oh and while we are at SQL topic, you can also log the actual
generated SQL query in laravel so you can actually see what was the
final SQL getting generated. If you can post it here, it would help a
lot. Look here.
select * from listings where status = 'Active' and (type = 'Apartment' or type = 'Duplex' and quadrant_main = 'NW' or quadrant_main = 'SW');
What this query will actually produce is this:
Select any listing which is active and:
1. Type is an apartment, or,
2. Type is a duplex, or,
3. Quadrant is SW, and,
4. Quadrant is NW
So assuming you have a database like this:
id|type|quadrant_main
=====================
1|Apartment|NW
2|Apartment|SW
3|Apartment|NE
4|Apartment|SE
5|Duplex|NW
6|Duplex|SW
7|Duplex|NE
8|Duplex|SE
9|House|NW
10|House|SW
11|House|NE
12|House|SE
You will only receive 1, and 5 in the result set. This result set is obviously wrong, plus it is depended on NW because that was the and condition.
The correct SQL query would be:
select * from listings where status = 'Active' and (type = 'Apartment' or type = 'Duplex') and (quadrant_main = 'NW' or quadrant_main = 'SW');
So structure your L5 app such that it produces this kind of SQL query. Instead of trying to cram everything in one loop, have two loops. One loop should only handle type and another loop should only handle quadrant_main. This way you will have the necessary and condition in the right places.
As a side note:
Never directly use user input. Always sanitize it first.
Its not a best practice to put all your logic in the controller. Use repository pattern. See here.
Multiple where clauses are generally applied via Criteria. Check that out in the above linked repository pattern.
You code logic is very complicated and utterly un-necessary. Instead of sending JSON objects, simply send the state of checkboxes. Don't try to generalize the function by going in loop. Instead handle all checkboxes one by one i.e. is "Apartments" selected, if yes, add that to your clause, if not, don't add.
I've written the following query (that may or may not be efficient, I'm still a newbie):
$collection = $this->dm->getConnection()->selectCollection('db_name', 'collection_name');
$query = array('array_name' => new \MongoId(id));
$cursor = $collection->find($query)->limit(9)->sort('r', 'desc');
I'm trying to sort by an r value that looks like this in the document:
"r": 0.58325652219355106354
but it isn't actually sorting it by that r-value. What am I doing wrong?
Pretty sure sort takes an array argument. Try
->sort(['r' => 'desc]);
I looked it up...
http://apigen.juzna.cz/doc/doctrine/mongodb/source-class-Doctrine.MongoDB.Cursor.html#564-585
The title asks it all.
I have found an example that looked something like this:
db.find(fields = {"-id"}).sort("-id", -1).limit(X)
but that doesn't seem safe because that is assuming the ids will actually be in order.
$item = array( ... );
$mongo_collection->insert($item);
$id = $item['_id'];
It'll add the ID to the $item array. Also note you can use an object instead of an array if it's your preference.