How can I prevent CakePHP from escaping data on a save?

余生颓废 提交于 2019-12-13 02:35:17

问题


I am doing some PostGIS work on a CakePHP application.

Because I've been working with some database functions, I've done raw $this->query() calls to do inserts of data. I'm at a point where I need to get the ID of the result of an insert query, but $this->query() returns an empty array.

Here is the query I'm using for inserts:

INSERT INTO locations (title,company_id,state_id,poly,point) 
VALUES ('$title',$company_id,$state_id,ST_GeomFromText('$geom',4269),$point);

The problem is Cake is trying to insert 'ST_GeomFromText('$geom',4269)' as a string, and I cannot figure out how to get it to remove the quotes in the SQL insert statement it prepares via $this->Location->save();.

Any suggestions?

Edit:

Before I was doing $this->query(); and my SQL works fine. That's not the issue.

Now when I do:

$this->Location->create();
$this->Location->set('poly',$poly);

... Set all the rest of the model fields ...

$this->Location->save();

The SQL that gets produced looks like this:

INSERT INTO locations (title,company_id,state_id,poly,point) 
VALUES ('Some Title',5,23,'ST_GeomFromText('$geom',4269)',POINT(-72.342,102.23455);

Because ST_GeomFromText gets 'quoted', PostgreSQL throws an error and doesn't insert the geometry.


回答1:


The solution to my problem turned out to NOT be a CakePHP based one, but a PostgreSQL one!

By appending "RETURNING id" to the query like this:

INSERT INTO locations (title,company_id,state_id,poly,point) 
VALUES ('$title',$company_id,$state_id,ST_GeomFromText('$geom',4269),$point) RETURNING id;

The query no longer returns an empty array, and now returns the ID of the row it just created!




回答2:


Via $this->ModelName->getLastInsertID(); you are able to get the last inserted ID. So, after a save you can call this code to get its id.



来源:https://stackoverflow.com/questions/18723248/how-can-i-prevent-cakephp-from-escaping-data-on-a-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!