Prepared statements with TBS - tinybutstrong

I'm trying to merge the results of a prepared statement to TBS. Here's my code:
$s = $link->prepare("SELECT * FROM newsletters WHERE newsletter_id = :newsletter_id");
$s->bindParam(":newsletter_id",$newsletter_id);
$s->execute();
$newsletter = $s->fetch(PDO::FETCH_ASSOC);
$tbs->MergeBlock('$newsletter ', $newsletter );
But I can't get the results fields. I get errors like the following:
TinyButStrong Error in field [newsletter.title...]: item 'title' is not an existing key in the array.
I can't find my error.

MergeBlock() is for merging a recordset , so you should use $s->fetchAll() instead of $s->fetch(). The section of the template will be repeated for each record.
But if you have to merge a standalone record, use MergeField() instead of MergeBlock(). The single fields will be merged one by one without repeating.

Related

Doctrine: select rows that are related to another table

I have two tables: assignment and file that is related to assignment. I would like to get rows of assignment that are related to any row of file applying the where sentence.
$querybuilder = $this->createQueryBuilder('query');
$querybuilder
->select('assignment')
->from(AssignmentReadModel::class, 'assignment')
->innerJoin('assignment.files', 'files')
->where('files.name=:archivo')
->setParameter('archivo', 'practica');
$data = $querybuilder->getQuery()->getResult();
$files = $data[0]->files();
var_export($files->count());
With this query I'm getting all the files when it should only get only one file "practica". When I execute "$files->count()" doctrine is doing a extra query to get all the files.
In query, no columns of the files entity are selected, so this is not part of the result rows and thus the relation is not hydrated.
To get the filtered files, select also the files relation:
$querybuilder
->select('assignment')
->addSelect('files')
A word of caution
Once a relation has been hydrated, this hydrated collection is used for this entity for other queries(reference all result row doesn't fetch in object, unless you choose to
1) refresh the collection:
$em->refresh($assignment);
and also include refrech option on cascade operations of the relation definition:
#OneToMany(targetEntity="File", mappedBy="assignment", cascade={"refresh"})
or
2) when using query builder to set:
use Doctrine\ORM\Query;
$querybuilder->setHint(Query::HINT_REFRESH, true); // <-- Tell the hydrator to refresh

Laravel query builder - Select elements unique or null on specific column

I have a model Form for table forms. There is a column called guid which can be null, or contain some sort of grouping random hash.
I need to select all forms that have column guid either null or unique in current search. In other words, for repeating guid values in current search I select only first occurence of every guid hash.
I tried:
$results = App\Form::where(... some where clauses .. ).groupBy('guid')
and it's almost ok, but for all rows, where guid == NULL it groups them and selects only one (and I need all of them).
How can I get the unique or null rows either by building proper SQL query or filtering the results in PHP?
Note: I need my $results to be an Illuminate\Database\Eloquent\Builder instance
EDIT:
I fount out that SQL version of query I need is:
SELECT * FROM `forms` WHERE .... GROUP BY IFNULL(guid, id)
What would be equivallent query for Laravel's database query builder?
UPDATE: Using DB::raw
App\Form::where(... conditions ...)
->groupBy(DB::raw("IFNULL('guid', 'id')"));
Or the another way could be:
You can also use whereNotNull, whereNull & at last merge both the collections using merge() like this:
First get the results where guid is grouped by (excluding null guid's here):
$unique_guid_without_null = App\Form::whereNotNull('guid')->groupBy('guid')->get();
Now, get the results where guid is null:
$all_guid_with_null = App\Form::whereNull('guid')->get();
and at last merge both the collections using merge() method:
$filtered_collection = $unique_guid_without_null->merge($all_guid_with_null);
Hope this helps!
For your edited question, you can use raw() as;
->groupBy(DB::raw("IFNULL('guid', 'id')"))
So your final query will be as:
$results = App\Form::where(... some where clauses .. )
->groupBy(DB::raw("IFNULL('guid', 'id')"));
By above query, your $results will be an instance of Illuminate\Database\Eloquent\Builder.

Yii2- Not able to insert/delete rows using console controller

I am trying to implement email queue in my project which uses CRON.
I am adding a row in one table and deleting a row from another table using CreateCommand of yii2. Database is mysql.
The entire code is executed and it does not display any error. But the rows are not added or deleted from the database.
I have also tried doing the same thing using ActiveRecords but it does not work. Hence I have used CreateCommand.
Below is the code which I am using -
$connection = \Yii::$app->db;
$result = $connection->createCommand()->insert('email_queue_completed', $arrInsert)->execute();
if(!empty($result))
{
$connection->createCommand()
->delete('email_queue', ['id' => $mail->id])
->execute();
}
$arrInsert is an array containing key value pairs of values to be inserted.

Write query which run on array by considring sub query in Parse

I need to write a query in such way that the array(collection) is contain only sub query objects.
Suppose we have the two tables as follows:
TableA:
objectId, name
TableB:
objectId, names[array of name: parse pointer collection]
Here is my code which I tried:
// sub query
var subQuery = new Parse.Query('TableA');
subQuery.doesNotExist('name');
// main query
var query = new Parse.Query('TableB');
query.exists("names");
//query.containsAll("names", subQuery); // this means names should contain all subQuery, so this is not use full for me.
query.matchesQuery("names", subQuery);
This code is running fine, but this is not working as I want and also not showing the any error.
It seems that you don't need a subquery per se, but rather to first query your list of names, and then use that in your main query. What you seem to be looking for is: containedIn( key, values ) , as in:
query.containedIn("name", namesFromFirstQuery)

How to remove records from a dataset with LINQ

I have a dataset (called dataSet below) with a single table and some records in it. One of the columns is called Message and contains an error message. If any records have a value in this field I want to copy it into an error dataset (errorDataSet below) and then remove it from the original dataset. I managed to get this far with LINQ:
DataSet errorDataSet = dataSet.Copy();
//find all records that have a Message column value
var query = from row in errorDataSet.Tables[0].AsEnumerable()
where !String.IsNullOrEmpty(row.Field<string>("Message"))
select row;
DataSet tempErrorDataSet = errorDataSet.Clone();
foreach (var row in query)
{
tempErrorDataSet.Tables[0].Clear();
tempErrorDataSet.Tables[0].ImportRow(row);
utility.WriteError(connectorName, row["Message"].ToString(), tempErrorDataSet);
//remove the error row from the good data
dataSet.Tables[0].Rows.Remove(row);
}
The bottom line throws an exception or I get errors regarding modifying a collection etc. I'm sure there is a simple way of doing this in LINQ.
Note: The reason I have tempErrorDataSet is that I convert it to XML and pass it into a stored proc - it only takes a record at a time in that format, hence I clear it each time.
Your query is enumerating (indirectly) through the rows in the table. As you should already know, you cannot modify a collection (remove something in this case) as you enumerate over it. Throw the contents into a list beforehand. That way you're not enumerating through the actual table but a copy of some rows.
var query = (from row in errorDataSet.Tables[0].AsEnumerable()
where !String.IsNullOrEmpty(row.Field<string>("Message"))
select row).ToList();

Resources