|
1 | 1 | # Easy Query |
2 | 2 |
|
3 | | -CakePHP behavior plugin for easily some complicated queries like upsert, bulk upsert and bulk insert. |
| 3 | +CakePHP behavior plugin for easily some complicated queries. |
4 | 4 |
|
5 | 5 | [](https://travis-ci.org/itosho/easy-query) |
6 | 6 | [](https://codecov.io/gh/itosho/easy-query) |
@@ -83,6 +83,62 @@ $entities = $this->Articles->newEntities($data); |
83 | 83 | $this->Articles->bulkInsert($entities); |
84 | 84 | ``` |
85 | 85 |
|
| 86 | +### Insert Select |
| 87 | +For inserting a record just once. |
| 88 | + |
| 89 | +#### case1 |
| 90 | +Specify search conditions. |
| 91 | + |
| 92 | +```php |
| 93 | +$this->Articles = TableRegistry::get('Articles'); |
| 94 | +$this->Articles->addBehavior('Itosho/EasyQuery.Insert'); |
| 95 | + |
| 96 | +$data = [ |
| 97 | + 'title' => 'New Article?', |
| 98 | + 'body' => 'New Article Body?' |
| 99 | +]; |
| 100 | +$entity = $this->Articles->newEntity($data); |
| 101 | +$condition = [ |
| 102 | + 'title' => 'New Article?' |
| 103 | +]; |
| 104 | + |
| 105 | +$this->Articles->insertOnce($entities); |
| 106 | +``` |
| 107 | + |
| 108 | +Generated SQL is below. |
| 109 | + |
| 110 | +```sql |
| 111 | +INSERT INTO articles (title, body) |
| 112 | +SELECT 'New Article?', 'New Article Body?' FROM tmp WHERE NOT EXISTS ( |
| 113 | + SELECT * FROM articles WHERE title = 'New Article?' |
| 114 | +) |
| 115 | +``` |
| 116 | + |
| 117 | +#### case2 |
| 118 | +Auto set search conditions with a inserting record. |
| 119 | + |
| 120 | +```php |
| 121 | +$this->Articles = TableRegistry::get('Articles'); |
| 122 | +$this->Articles->addBehavior('Itosho/EasyQuery.Insert'); |
| 123 | + |
| 124 | +$data = [ |
| 125 | + 'title' => 'New Article', |
| 126 | + 'body' => 'New Article Body' |
| 127 | +]; |
| 128 | +$entity = $this->Articles->newEntity($data); |
| 129 | + |
| 130 | +$this->Articles->insertOnce($entities); |
| 131 | +``` |
| 132 | + |
| 133 | +Generated SQL is below. |
| 134 | + |
| 135 | +```sql |
| 136 | +INSERT INTO articles (title, body) |
| 137 | +SELECT 'New Article', 'New Article Body' FROM tmp WHERE NOT EXISTS ( |
| 138 | + SELECT * FROM articles WHERE title = 'New Article' AND body = 'New Article Body' |
| 139 | +) |
| 140 | +``` |
| 141 | + |
86 | 142 | ### Advanced |
87 | 143 | Need to use `Timestamp` behavior, if you want to update `created` and `modified` fields automatically. |
88 | 144 | And you can change the action manually by using `event` config like this. |
|
0 commit comments