As an follow up idea to solve my "sort product collection by sub-category" problem explained in my question sorting collections by subcategory, an attribute and by productname I had the idea to add a AS expression to the selected fields of the collection.
What I want to achieve (SQL-wise) is something like this:
SELECT field1, 'some string' as 'category_name' FROM ...
So I thought I could use the addExpressionFieldToSelect in the method chain to dynamically add the category name string to the products collection.
For that have the following:
// ...
$_products = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addExpressionFieldToSelect('\'some category name\'', 'AS', 'category_name')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->addAttributeToFilter('is_saleable', array('like' => '1'))
->addAttributeToFilter('category_id', $_subcategory_finset_ids)
->addAttributeToSort('ws_geschmack', 'ASC')
->addAttributeToSort('name', 'ASC');
// ...
But with that I get an error:
Fatal error: Call to undefined method Mage_Catalog_Model_Resource_Product_Collection::addExpressionFieldToSelect() ...
Short explanation: In fact I am not able to sort product collections by sub-category (string) I first query all child categories of a parent category (ordered) and within a loop I query all products of these child categories (down to the deepest level) to get products sublists of each subcategory and sub-sub categories. To fully understand my problem, please refer to my question mentioned above.
It is just a try, I do not know if all this is really working. As a hack for now I just try to come a little closer with that AS expression field holding the category name of the outer loop. I then could merge these collections and would have a final products collection.
If there is a more simple way, please let me know.
Any help is greatly appreciated!!
Update
Instead of using addExpressionFieldToSelect it is possible to use this:
$_products->getSelect()
->columns(
array(
'category_name' => new Zend_Db_Expr(
'some string')
)
);
As stated above in my update, I solved the problem by using:
$_products->getSelect()
->columns(
array(
'category_name' => new Zend_Db_Expr('some string')
)
);
In fact, simple solution!
Related
I have a table with multiple column and I want to return a column name using another column name as search criteria. How do I achieve this in yii2?
Below is sample code, normal sql should be:
$name = SELECT type_name FROM ProductTable WHERE type_id = 1;
echo $name;
This should return the value of the column type_name where the value of the column type_id equals 1. I tried this, but it doesn't work
$type_name = ProductTable::find()->where(['type_id' =>$model->type_id]);
$type_name = Product::find(['type_name'])->where(['type_id' =>$model->type_id]);
I also tried this, but I guess it was wrong
I hope my question is clear enough and any help will he appreciated
and u could also use createCommand!
$name = \Yii::$app->getDb()->createCommand("SELECT type_name FROM ProductTable WHERE type_id=:typeId", ['typeId'=>$model->type_id])->queryAll();
For a general introduction to Yii2's ActiveRecord, see the guide: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
If you want the complete row and have a model, you're just missing a one():
Product::find()->where(['type_id' =>$model->type_id])->one();
If you do have a Model defined and just want a single value, try:
Product::find()->select('type_name')->where(['type_id' =>$model->type_id])->scalar();
Which basically generates an ActiveQuery via the model, and changes it to return only the first column in the first row of matched results.
If you do NOT have a model, you could also generate a normal query without ActiveRecord usage (http://www.yiiframework.com/doc-2.0/yii-db-query.html)
$name = (new Query())->select('type_name')
->from('ProductTable')
->where(['type_id' =>$model->type_id])
->scalar();
I assume you generated ProductTable by using Gii module.
Also, if type_id column is a primary key:
$product = ProductTable::findOne($model->type_id);
if($product !== null) { $product->typeName /*... read value ...*/}
or to get all records
$products = ProductTable::findAll($model->type_id); //match all records.
for any other column use the following syntax instead:
$product = ProductTable::findOne(['type_id' => $model->type_id]);
Use following code to get type_name
$PTable=ProductTable::find()->select('type_name')->where(['type_id' =>$model->type_id])->one();
echo $PTable->type_name;
Hi have a text search input that looks for matching records in the DB and gets all the data from a table:
let's say like this:
$q = Input::get('items');
$q = "\"" . "($q)" . "\"";
$items = DB::table('my_items')->whereRaw(
'MATCH(item_name) AGAINST(? IN BOOLEAN MODE)',
array($q)
)->get();
So I get all the items in the DB from my textsearch, then I send the result as json to some script that updates my page with the items:
return Response()->json($items);
The relations are:
My_item:
public function brand(){
return $this->hasOne('App\Brand', 'id', 'brand_id');
}
Brand:
public function My_item(){
return $this->belongsToMany('App\My_item');
}
Now the problem here is that in 'my_items' table I have some data as IDs that reference foreign tables.
For example I will have a 'brand_id' that for example references a 'brands' table where I can have information regarding the brand.
So for example I could have brand_id = 3 that means 'Microsoft' in my brands table (id = 3, name = microsoft).
Now what I need to do is not only passing the brand_id to my view but also the actual information (name), in this case Microsoft so that I can put that info in the item description.
But, how can I get that information before sending with that query? Is there some sort of flag I can use in the query like $items = DB::table bla bla with foreign?
this way works, DB:: method is dropped for:
$items = My_item::with('brand')->where('item_name', 'LIKE', "%$q%")->get();
this one doesn't:
DB::table('my_items')::with('brand')->where('item_name', 'LIKE', "%$q%")->get();
First of all, you can simplify your search query to something like this:
My_item::where('item_name', 'LIKE', "%$q%")->get();
Now, assign relations the relation to your other tables in your Models. Then you can get all information using the following syntax:
My_item::with('brand')->where('item_name', 'LIKE', "%$q%")->get();
Read more about relations here: https://laravel.com/docs/5.1/eloquent-relationships
I'm trying to do native SQL in Doctrine. Basically I have 2 parameters:
CANDIDATE_ID - user for who we delete entries,
list of FILE_ID to keep
So I make
$this->getEntityManager()->getConnection()->
executeUpdate( "DELETE FROM FILE WHERE CANDIDATE_ID = :ID AND NOT ID IN :KEEPID",
array(
"ID" => $candidate->id,
"KEEPID" => array(2) )
);
But Doctrine fails:
Notice: Array to string conversion in D:\xampp\htdocs\azk\vendor\doctrine\dbal\lib\Doctrine\DBAL\Connection.php on line 786
Is this bug in Doctrine? I'm making somewhere else select with IN but with QueryBuilder and it's working. Maybe someone could suggest better way of deleting entries, with QueryBuilder for example?
$stmt = $conn->executeQuery('SELECT * FROM articles WHERE id IN (?)',
array(array(1, 2, 3, 4, 5, 6)),
array(\Doctrine\DBAL\Connection::PARAM_INT_ARRAY)
);
From Doctrine's documentation.
You can't pass an array of IDs to a parameter. You can do this for scalar values, but even if this had a 'toString', it wouldn't be what you want.
String concatenation is one method,
"DELETE FROM FILE WHERE CANDIDATE_ID = :ID AND NOT ID IN (". implode(",", $list_of_ids) .")"
But this method goes straight around parameters, and therefore suffers in terms of readability, and is limited to a certain maximum line length, which can vary between databases.
Another approach is to write a function returning a table result, which takes a string of IDs as a parameter.
You could also solve this with a join to a table containing the IDs to keep.
It's a problem I've seen many times with few good answers, but it's usually caused by a misunderstanding in the way the database is modelled. This is a 'code smell' for database access.
I have a List(Of Hardware) - the List is called HWModels
Class Hardware has the following Properties:
ModelName
Status
CPUStatus
MemoryStatus
DiskStatus
The List is populated by reading a CSV file, once it's populated, I want to return the distinct records based on the ModelName
I've attempted by doing it as follows:
(From a In HWModels Select a.ModelName).Distinct
But this isn't right because I end up with a list of only the ModelName's and nothing else.
How do I get the Distinct function to return all of the other class members within the list?
LINQ to Objects doesn't provide anything to do "distinct by a projection" neatly. You could group by the name and then take the first element in each group, but that's pretty ugly.
My MoreLINQ provides a DistinctBy method though - in C# you'd use:
var distinct = HWModels.DistinctBy(x => x.ModelName).ToList();
Presumably the VB would be something like
Dim distinct = HWModels.DistinctBy(Function(x) x.ModelName).ToList
Apologies for any syntax errors though :(
This will group your objects by the preferred property and then will select the first of each one, removing duplicates.
Dim newlist = HWModels.GroupBy(Function(x) x.ModelName).Select(Function(x) x.First).ToList
I'm attemping to do a simple check for an empty collection in an NHIbernate Query. Here's my code:
var query = QueryNotDeleted().Where(x=>x.Markets.Count() > 0);
QueryNotDeleted returns an IQueryOver. The above line throws an error (Unrecognised method call in epression x.Markets.Count()) because it doesn't recognize the Count() in the query.
I tried
var query = QueryNotDeleted().Where(x=>x.Markets != null);
But unfortunately, Markets is never NULL, so I have to test for a count instead of it being null to get the records I want.
How can I get this "count" syntax correct so that it excludes records where the Markets property is empty?
I was able to get it to work using:
query.RootCriteria.CreateAlias("Markets", "m", JoinType.LeftOuterJoin);
and then
query.RootCriteria.Add(Restrictions.IsNotNull("m.Id"));
If I understand your question correctly you want to get a list of records that don't have corresponding children?
If I wanted to get a list of Orders that have no OrderItems using QueryOver then I would do something like:-
var orders = session.QueryOver<Order>()
.Left.JoinQueryOver(w => w.Items)
.Where(w => w.Order.Id == null);
If this is not the right answer then please can you submit the SQL you are trying to run and the parent/children mappings/.