I need to write this SQL query in Propel 2.0
SELECT RequestUser.userID, requests.requestID, requests.created, Responses.created, Responses.response, Responses.createdby_userID FROM requests
LEFT JOIN requestusers RequestUser ON (requests.requestID=RequestUser.requestID)
LEFT JOIN responses Responses ON (requests.requestID=Responses.requestID AND RequestUser.userID=Responses.createdby_userID)
WHERE requests.supportstatusID=3
and requests.requestid=50208;
Most important is the second join, it has multiple conditions.
I for the life of me cannot figure this out.
Any ideas?
I have used the Criteria class to AddMultipleJoins() but to no avail.
$pendingRequests = RequestQuery::create($criteria)
->select(['RequestUser.UserId', 'Request.Id', 'Request.CreatedDate'])
->leftJoin('Request.RequestUser RequestUser')
->leftJoin('Request.Response Responses')// <------ I need this line to have multiple conditions
->filterBySupportStatusId(3)
->find();
Okay I figured it out using this:
->addJoinCondition('JoinName', 'LeftColumn=?', 'RightColumn')
This adds an extra condition to the join!
Related
I tested the code below it works fine on phpmyadmin
SELECT registered_user_tbl.username, follow.follower_id FROM registered_user_tbl
INNER JOIN follow
ON follow.follower_id= 5 and registered_user_tbl.user_id= 5
I now want to implement the array version on my pdo project but it is not working kindly check and review query below
$this->db->select("SELECT registered_user_tbl.username, follow.follower_id FROM registered_user_tbl
INNER JOIN follow
ON follow.follower_id= :fid and registered_user_tbl.user_id= :fid",
(":fid" =>$user));
The 2nd parameter to your select() method should probably be an array so the round brackets are incorrect, for your data parameters.
And you cannot reuse :fid twice in the parameter substitution.
So try this
$this->db->select(
"SELECT registered_user_tbl.username, follow.follower_id
FROM registered_user_tbl
INNER JOIN follow ON follow.follower_id= :fid1
and registered_user_tbl.user_id= :fid2",
[":fid1" =>$user, ":fid2" =>$user]
);
I would like to execute such a command:
SELECT number.phone_number
FROM number
LEFT JOIN ordered_number
ON ordered_number.number_id=number.id
WHERE ordered_number.order_id=123
with Yii2. I do this:
$numery = Number::find()
->select('number.phone_number')
->leftJoin('ordered_number', ['ordered_number.number_id' => 'number.id'])
->where(['ordered_number.order_id' => 123])
->createCommand()
->rawSql;
But I get then this:
'SELECT `number`.`phone_number` FROM `number` LEFT JOIN `ordered_number` ON `ordered_number`.`number_id`='number.id' WHERE `ordered_number`.`order_id`=123'
Which doesn't work. When I put the first thing right into my base, I get 4 results, which is correct. But when I do (I think exactly the same) with Yii, I have troubles, because it is null. The only differences between what I have written and what appears after rawSql, are ` and '.
Sorry, I've just read docs for this method - it should be:
->leftJoin('ordered_number', 'ordered_number.number_id = number.id')
because using the where() kind of conditions with array leads to comparing field to string.
Maybe this link could help you a lot , the comments of ActiveRecord.
I have this strange situation and not sure of what is wrong. I have a simple self join to find matches based on some conditions. I have this query running fine in mysql but when I call it through PHP, it doesn't return any values.
select * from Requests p inner join Requests c on c.ID<>p.ID
where usr_ID<>4
and p.c_ID = c.c_ID
This works fine but not the below one.
DB::table('Requests as parent')
->join('Requests as child', 'parent.ID', '<>', 'child.ID')
->where('parent.usr_ID', '<>', 4)
**->where('parent.c_ID', '=', 'child.c_ID')**
->get();
In the above query, if I remove the second where condition(c_ID), it returns correct values. For all rows, this has a value of 1. If I replace child.c_ID or parent.c_ID by 1, it works again. I have tried with other columns as well and found the same issue.
Any pointers?
What the query builder makes out of your second where condition is:
WHERE parent.c_ID = 'child.c_ID'
So instead of a "normal" where() use whereRaw(), which takes your input and injects it right into the final SQL query
->whereRaw('parent.c_ID = child.c_ID')
Alternatively you could also use DB::raw() on the third argument
->where('parent.c_ID', '=', DB::raw('child.c_ID'))
Both are essentially the same so use whichever you like more.
With the help of this community, I was able to produce a query using an inner join which I thought would work for what I'm trying to do. Unfortunately, when I attempted to run the query found below, I received the following error:
ERROR: table name "bue" specified more than once
From what I've read on Google, some people have said that the "FROM bue" is not needed, but when I removed this, I got another error found below:
ERROR: syntax error at or near "INNER" at character 98
I'd very much appreciate your assistance in troubleshooting this. Thank you so very much.
Query:
UPDATE
bue
SET
rgn_no = chapterassociation.rgn_no,
chp_cd = chapterassociation.chp_cd
FROM
bue
INNER JOIN
chapterassociation
ON bue.work_state = chapterassociation.work_state
AND bue.bgu_cd = chapterassociation.bgu_cd
WHERE
bue.mbr_no IS NULL AND bue.chp_cd IS NULL
In PostgreSQL, specifying the table to be updated needs to be done only in the UPDATE clause, e.g. UPDATE bue. The FROM clause is only for additional tables referenced in the query. (If you were doing a self-join on bue, you would mention it again in the FROM clause, but you aren't in this case.)
The second error you get is likely just a simple syntax error. The other tricky thing is that JOIN/ON syntax doesn't fit in the FROM clause, so you have to move the join conditions to the WHERE clause. Try something like:
UPDATE
bue
SET
rgn_no = chapterassociation.rgn_no,
chp_cd = chapterassociation.chp_cd
FROM
chapterassociation
WHERE
bue.mbr_no IS NULL AND bue.chp_cd IS NULL
AND bue.work_state = chapterassociation.work_state
AND bue.bgu_cd = chapterassociation.bgu_cd
See http://www.postgresql.org/docs/current/interactive/sql-update.html.
(N.B. At least I don't know how to put JOIN/ON into an UPDATE statement... I could be missing something.)
I have a controller action that uses a sql query:
$tag = $this->params['tag'];
$this->set('projects', $this->Project->query('SELECT * FROM projects INNER JOIN projects_tags ON projects.id = projects_tags.project_id INNER JOIN tags on projects_tags.tag_id = tags.id WHERE tags.tag LIKE $tag'));
As you can see at the end I want to use a where clause with the $tag variable but I'm not sure how the syntax would go. As I'm getting the error
Unknown column '$tag' in 'where clause'
Can someone steer me in the right direction?
Ta,
Jonesy
I would strongly advise you to use the Cake ORM instead of raw queries, especially if you're going to plug URL parameters into it. Conditions on HABTM tables can be tricky, but you can build your joins using Cake's ORM syntax as well!
Read the manual, section 3.7.6.9 Joining tables.
Should you want to use Cake's ORM, the following code should provide results equivalent to your raw SQL query:
$this->loadModel('ProjectsTag'); // Load the joining table as pseudo-model
// Define temporary belongsTo relationships between the pseudo-model and the two real models
$this->ProjectsTag->bindModel(array(
'belongsTo' => array('Project','Tag')
));
// Retrieve all the join-table records with matching Tag.tag values
$result_set = $this->ProjectsTag->find('all',array(
'conditions' => array('Tag.tag LIKE' => "%{$tag}%")
));
// Extract the associated Project records from the result-set
$projects = Set::extract('/Project', $result_set);
// Make the set of Project records available to the view
$this->set(compact('projects'));
in php there's a difference between single and double quotes... basically, single quotes dont evaluate the variables... use double quotes instead
And i think that LIKE will need also single quotes.. i'm not really sure
"SELECT * FROM projects INNER JOIN projects_tags ON projects.id = projects_tags.project_id INNER JOIN tags on projects_tags.tag_id = tags.id WHERE tags.tag LIKE '$tag'"
i know.. i know.. people will start talkin' about sql injection.. and the need to scape the caracters... that's another question =)
good luck!
I would at least consider using the cakephp sanitize functions on your tag strings if they are user sourced. See http://book.cakephp.org/view/1183/Data-Sanitization or if using mysql as the db at least consider using http://www.php.net/manual/en/function.mysql-escape-string.php or do something to filter your user input. But the best thing is to make use of the CakePHP orm stuff.
Modify your query as:
$this->set('projects',
$this->Project->query("SELECT * FROM projects
INNER JOIN projects_tags
ON projects.id = projects_tags.project_id
INNER JOIN tags ON projects_tags.tag_id = tags.id
WHERE tags.tag LIKE '" . $tag . "'") //problem was here
);
and it will work.