I have a problem with symfony2 record insertion
My requirement is to find out all the users who are in between particular ages and the given column is dob.
I am getting the result with this mysql query.
SELECT * FROM app_users WHERE YEAR(CURDATE())-YEAR(dob) BETWEEN 10 AND 20;
How to rewrite this query in the symfony- doctrine fromat?
Pls help...
$qb = $em->createQueryBuilder();
$qb->select('au')
->from('AppUsers au)
->where($qb->expr()->between('YEAR(CURDATE())-YEAR(au.dob)', 10,20));
$result = $qb->getQuery()->getResult();
I have not checked it. but it may help you.
Related
I have 2 databases(one in mySql and the other one in MongoDB) in my project and I need to perform a query like this
public function getPosts() {
$user = Auth::user();
$follow = DB::connection("mongodb")
->collection("followers")
->where("user_id", $user->id)->get();
/*$res = DB::select("
SELECT *
FROM posts
WHERE user_id = ? OR user_id IN
(SELECT user_id from $follows)
ORDER BY created_at DESC", [$user->id, $user->id]);
*/
return response()->json($res);
}
This is a query which returns the posts from the logged user and from people the user follow
The followers table (the one in MongoDB) contains "user_id" and "follows_id"
The commented line is the original query (every table in one single database on mySql
Thank you
Edit: I solved through a query in mongodb, then I edited the result to get an array which I incorporated into the sql query through orWhereIn Thank you for your answers :)
I don't think so... you may try a true multimodel database such as Oracle XE (it's free) to achieve your goal here...
I want to compare a stored DateTime entry in my Database with the current date using Doctrine.
I have a list of Keys and their relation to a Person. My goal now is to create a list for available keys or not available keys.
For that I have to look at 2 Tables, key and personToKey. Where personToKey has a field rueckgabe(time to return the key) (dateTime) and a field key (stored id of the key) with an OneToMany Relation to the field id of the Table key.
Thanks to some search here, I got a running SQL Query which gives me the values I am looking for.
SQL Query:
SELECT * FROM key LEFT OUTER JOIN personToKey on key.id = personToKey.KeyId
WHERE personToKey.rueckgabe < NOW()
My Problem is now, that I don't get this to work using doctrine. I had 2 approaches for this.
$qb = $em->createQueryBuilder();
$query = $qb->select('k')
->from('MyBundle:key', 'k')
->leftjoin('MyBundle:personToKey', 'ptk','WITH', 's.id = ptk.key')
->where('ptk.rueckgabe < :date_now')
->setParameter('date_now', date('Y-m-d H:i:m'))
->getQuery();
$test = $query->getResult();
And
$sql = 'SELECT k FROM MyBundle:key k LEFT OUTER JOIN MyBundle:PersonToKey ptk WITH k.id = ptk.key WHERE ( ptk.rueckgabe < CURRENT_DATE()) ';
$query = $em->createQuery($sql);
$test = $query->getResult();
Since the SQL Query works I would have thought that at least the second approach should have worked. But in both cases I get the following results:
for ptk.rueckgabe >= :date_now the list is fine, but for ptk.rueckgabe < :date_now I get a mix of available and not available keys. Also the length of the result is below the number of rows the SQL Query finds in PHPMyAdmin.
Thanks in advance.
As the answer here states:
The equivalent of MySQL's NOW() is Doctrine DQL's CURRENT_TIMESTAMP().
CURRENT_DATE() only returns the date part.
This might explain, why the second approach did not give the same result as running a straight SQL query.
For the first approach you could try the following, even though I am not sure if it will make a difference:
->setParameter('date_now', new \DateTime())
Edit:
I found another potential problem in your QueryBuilder:
Instead of
->leftjoin('MyBundle:personToKey', 'ptk','WITH', 's.id = ptk.key')
you could try to write:
->leftjoin('k.personToKey', 'ptk')
The s.id was definitely wrong, not sure about the rest.
I finally found a working solution for my Problem, so I wanted to share it, if other People have a similar problem.
$now = new \DateTime() ;
$now1=$now->format('Y-m-d H:i:s');
$sql = 'SELECT * FROM key AS k
LEFT OUTER JOIN persontoKey AS ptk ON k.id = ptk.keyId
WHERE ( ptk.rueckgabe < :now ) ';
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->bindValue('now', $now1, \PDO::PARAM_STR);
$stmt->execute();
$helper= $stmt->fetchAll();
Suppose I have table A with its active record in yii2, What is the best way to can load the record with max created date to the model.
This is the query :
select *
from A
where created_date = (
select max(created_date) from A
)
Now I am getting the max date first then use it in another access to database ie:
$max = A::find()->select("created_date)")->max();
$model = A::find()->where("created_date = :date",[":date"=>$max])->one();
I am sure that this can be done with one access to database , but I don't know how.
please any help.
Your query is the equivalent of:
SELECT * FROM A ORDER BY created_date DESC LIMIT 1;
You can order your records by created_date in descending order and get the first record i.e:
$model = A::find()->orderBy('created_date DESC')->limit(1)->one();
Why limit(1)? As pointed out by nicolascolman, according to the official Yii documentation:
Neither yii\db\ActiveRecord::findOne() nor yii\db\ActiveQuery::one() will add LIMIT 1 to the generated SQL statement. If your query may return many rows of data, you should call limit(1) explicitly to improve the performance, e.g., Customer::find()->limit(1)->one().
$maxdate=A::find()->max('created_date');
Try this
$model = A::find()->orderBy("created_date DESC")->one();
I'm trying to update a mySQL table using php. Basically I pass an ordernumber (int) and use it to find both isbn and quantityordered which I then use to update another table.
$orderID=$_POST["order_ent_number"];
$query="select ISBN from Orders where orderNumber='$orderID'";
$isbn = mysql_query($query) or die(mysql_error());
$query="select quantityOrdered from Orders where orderNumber='$orderID'";
$quantityordered = mysql_query($query) or die(mysql_error());
$query="UPDATE Books SET inStock='$quantityordered' WHERE inStock='0' AND isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
So using the MySQL bench, the query works (if I replace all variables with numbers) and changes it. The problem is when I use the variables in PHP, the code does not work. I tried the mysql_escape_string but that didnt work either. I checked the results of both variables $isbn and $quantityordered and they are right. I get no errors when I run it on the server but there is no change to inStock in the database. After searching around, someone said my variables need to be turned into integers? Not sure if this is correct or not but that is all I came up with. Any suggestions?
Actually you can do it in a single UPDATE statement by joining the tables,
UPDATE Books a
INNER JOIN Orders b
ON a.ISBN = b.ISBN
SET a.instock = a.quantityOrdered
WHERE a.instock = 0 AND
b.OrderNUmber = '$orderID' AND
a.ISBN = '$isbn'
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
maybe you can try
$query="select ISBN from Orders where orderNumber='".$orderID."'";
$query="select quantityOrdered from Orders where orderNumber='".$orderID."'";
$query="UPDATE Books SET inStock='".$quantityordered."' WHERE inStock='0' AND isbn='".$isbn."'";
Hi,
I need a help related to Codeigniter very badly.
I have some problems with a database query, i'am new to Codeigniter.
I have 3 tables:
1) film(film_id, filmname) PK (film_id)
2) category(category_id, categoryname) PK (category_id)
3) film_category(contains both primary keys (film_id) and (category_id))
The problem is that I want to select all filmname from film tables where category_id = 3.
How to do this with active record class?
Please make a suggestion.
I'am new to Codeigniter and I love it.
Thank you in advance from your friend.
Something like that:
$this->db->select('f.filmname');
$this->db->join('film_category fc', 'fc.film_id = f.film_id');
$this->db->where('fc.category_id', 3);
$query = $this->db->get('film f');
I find the ActiveRecord one of the most useful and elegant parts of CodeIgniter.
select data from the database in descending order
$this->db->order_by("id","desc");
$query = $this->db->get('table_name');
return $query->result();