手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表全部文章

值得收藏的yii2的doc中关于db Query的说明

 
Yii2的DB操作与1有很大的区别。所以下面这段还是值得收藏的
虽然第一句让我很简单,但没关系,大部分内容还是照用的,原文地址来自:https://github.com/yiisoft/yii2/blob/master/docs/guide/db-query-builder.md
 
为什么就没有cdbcriteria了呢?哎。。。
 

Note: This section is under development.

Yii provides a basic database access layer as described in the Database basics section. The database access layer provides a low-level way to interact with the database. While useful in some situations, it can be tedious and error-prone to write raw SQLs. An alternative approach is to use the Query Builder. The Query Builder provides an object-oriented vehicle for generating queries to be executed.

A typical usage of the query builder looks like the following:

$rows = (new \yii\db\Query())     ->select('id, name')     ->from('user')     ->limit(10)     ->all();  // which is equivalent to the following code:  $query = (new \yii\db\Query())     ->select('id, name')     ->from('user')     ->limit(10);  // Create a command. You can get the actual SQL using $command->sql $command = $query->createCommand();  // Execute the command: $rows = $command->queryAll();

Query Methods

As you can see, [[yii\db\Query]] is the main player that you need to deal with. Behind the scene, Query is actually only responsible for representing various query information. The actual query building logic is done by [[yii\db\QueryBuilder]] when you call the createCommand() method, and the query execution is done by [[yii\db\Command]].

For convenience, [[yii\db\Query]] provides a set of commonly used query methods that will build the query, execute it, and return the result. For example,

  • [[yii\db\Query::all()|all()]]: builds the query, executes it and returns all results as an array.
  • [[yii\db\Query::one()|one()]]: returns the first row of the result.
  • [[yii\db\Query::column()|column()]]: returns the first column of the result.
  • [[yii\db\Query::scalar()|scalar()]]: returns the first column in the first row of the result.
  • [[yii\db\Query::exists()|exists()]]: returns a value indicating whether the query results in anything.
  • [[yii\db\Query::count()|count()]]: returns the result of a COUNT query. Other similar methods include sum($q),average($q)max($q)min($q), which support the so-called aggregational data query. $q parameter is mandatory for these methods and can be either the column name or expression.

Building Query

In the following, we will explain how to build various clauses in a SQL statement. For simplicity, we use $query to represent a [[yii\db\Query]] object.

SELECT

In order to form a basic SELECT query, you need to specify what columns to select and from what table:

$query->select('id, name')     ->from('user');

Select options can be specified as a comma-separated string, as in the above, or as an array. The array syntax is especially useful when forming the selection dynamically:

$query->select(['id', 'name'])     ->from('user');

Info: You should always use the array format if your SELECT clause contains SQL expressions. This is because a SQL expression like CONCAT(first_name, last_name) AS full_name may contain commas. If you list it together with other columns in a string, the expression may be split into several parts by commas, which is not what you want to see.

When specifying columns, you may include the table prefixes or column aliases, e.g., user.iduser.id AS user_id. If you are using array to specify the columns, you may also use the array keys to specify the column aliases, e.g.,['user_id' => 'user.id', 'user_name' => 'user.name'].

Starting from version 2.0.1, you may also select sub-queries as columns. For example,

$subQuery = (new Query)->select('COUNT(*)')->from('user'); $query = (new Query)->select(['id', 'count' => $subQuery])->from('post'); // $query represents the following SQL: // SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`

To select distinct rows, you may call distinct(), like the following:

$query->select('user_id')->distinct()->from('post');

FROM

To specify which table(s) to select data from, call from():

$query->select('*')->from('user');

You may specify multiple tables using a comma-separated string or an array. Table names can contain schema prefixes (e.g. 'public.user') and/or table aliases (e.g. 'user u'). The method will automatically quote the table names unless it contains some parenthesis (which means the table is given as a sub-query or DB expression). For example,

$query->select('u.*, p.*')->from(['user u', 'post p']);

When the tables are specified as an array, you may also use the array keys as the table aliases (if a table does not need alias, do not use a string key). For example,

$query->select('u.*, p.*')->from(['u' => 'user', 'p' => 'post']);

You may specify a sub-query using a Query object. In this case, the corresponding array key will be used as the alias for the sub-query.

$subQuery = (new Query())->select('id')->from('user')->where('status=1'); $query->select('*')->from(['u' => $subQuery]);

WHERE

Usually data is selected based upon certain criteria. Query Builder has some useful methods to specify these, the most powerful of which being where. It can be used in multiple ways.

The simplest way to apply a condition is to use a string:

$query->where('status=:status', [':status' => $status]);

When using strings, make sure you're binding the query parameters, not creating a query by string concatenation. The above approach is safe to use, the following is not:

$query->where("status=$status"); // Dangerous!

Instead of binding the status value immediately, you can do so using params or addParams:

$query->where('status=:status'); $query->addParams([':status' => $status]);

Multiple conditions can simultaneously be set in where using the hash format:

$query->where([     'status' => 10,     'type' => 2,     'id' => [4, 8, 15, 16, 23, 42], ]);

That code will generate the following SQL:

WHERE (`status` = 10) AND (`type` = 2) AND (`id` IN (4, 8, 15, 16, 23, 42))

NULL is a special value in databases, and is handled smartly by the Query Builder. This code:

$query->where(['status' => null]);

results in this WHERE clause:

WHERE (`status` IS NULL)

You can also create sub-queries with Query objects like the following,

$userQuery = (new Query)->select('id')->from('user'); $query->where(['id' => $userQuery]);

which will generate the following SQL:

WHERE `id` IN (SELECT `id` FROM `user`)

Another way to use the method is the operand format which is [operator, operand1, operand2, ...].

Operator can be one of the following (see also [[yii\db\QueryInterface::where()]]):

  • and: the operands should be concatenated together using AND. For example, ['and', 'id=1', 'id=2'] will generate id=1 AND id=2. If an operand is an array, it will be converted into a string using the rules described here. For example, ['and', 'type=1', ['or', 'id=1', 'id=2']] will generate type=1 AND (id=1 OR id=2). The method will NOT do any quoting or escaping.

  • or: similar to the and operator except that the operands are concatenated using OR.

  • between: operand 1 should be the column name, and operand 2 and 3 should be the starting and ending values of the range that the column is in. For example, ['between', 'id', 1, 10] will generate id BETWEEN 1 AND 10.

  • not between: similar to between except the BETWEEN is replaced with NOT BETWEEN in the generated condition.

  • in: operand 1 should be a column or DB expression. Operand 2 can be either an array or a Query object. It will generate an IN condition. If Operand 2 is an array, it will represent the range of the values that the column or DB expression should be; If Operand 2 is a Query object, a sub-query will be generated and used as the range of the column or DB expression. For example, ['in', 'id', [1, 2, 3]] will generate id IN (1, 2, 3). The method will properly quote the column name and escape values in the range. The in operator also supports composite columns. In this case, operand 1 should be an array of the columns, while operand 2 should be an array of arrays or a Query object representing the range of the columns.

  • not in: similar to the in operator except that IN is replaced with NOT IN in the generated condition.

  • like: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing the values that the column or DB expression should be like. For example, ['like', 'name', 'tester'] will generatename LIKE '%tester%'. When the value range is given as an array, multiple LIKE predicates will be generated and concatenated using AND. For example, ['like', 'name', ['test', 'sample']] will generate name LIKE '%test%' AND name LIKE '%sample%'. You may also provide an optional third operand to specify how to escape special characters in the values. The operand should be an array of mappings from the special characters to their escaped counterparts. If this operand is not provided, a default escape mapping will be used. You may use falseor an empty array to indicate the values are already escaped and no escape should be applied. Note that when using an escape mapping (or the third operand is not provided), the values will be automatically enclosed within a pair of percentage characters.

    Note: When using PostgreSQL you may also use ilike instead of like for case-insensitive matching.

  • or like: similar to the like operator except that OR is used to concatenate the LIKE predicates when operand 2 is an array.

  • not like: similar to the like operator except that LIKE is replaced with NOT LIKE in the generated condition.

  • or not like: similar to the not like operator except that OR is used to concatenate the NOT LIKE predicates.

  • exists: requires one operand which must be an instance of [[yii\db\Query]] representing the sub-query. It will build a EXISTS (sub-query) expression.

  • not exists: similar to the exists operator and builds a NOT EXISTS (sub-query) expression.

Additionally you can specify anything as operator:

$query->select('id')     ->from('user')     ->where(['>=', 'id', 10]);

It will result in:

SELECT id FROM user WHERE id >= 10;

If you are building parts of condition dynamically it's very convenient to use andWhere() and orWhere():

$status = 10; $search = 'yii';  $query->where(['status' => $status]); if (!empty($search)) {     $query->andWhere(['like', 'title', $search]); }

In case $search isn't empty the following SQL will be generated:

WHERE (`status` = 10) AND (`title` LIKE '%yii%')

Building Filter Conditions

When building filter conditions based on user inputs, you usually want to specially handle "empty inputs" by ignoring them in the filters. For example, you have an HTML form that takes username and email inputs. If the user only enters something in the username input, you may want to build a query that only tries to match the entered username. You may use the filterWhere() method to achieve this goal:

// $username and $email are from user inputs $query->filterWhere([     'username' => $username,     'email' => $email, ]);

The filterWhere() method is very similar to where(). The main difference is that filterWhere() will remove empty values from the provided condition. So if $email is "empty", the resulting query will be ...WHERE username=:username; and if both $username and $email are "empty", the query will have no WHERE part.

A value is empty if it is null, an empty string, a string consisting of whitespaces, or an empty array.

You may also use andFilterWhere() and orFilterWhere() to append more filter conditions.

ORDER BY

For ordering results orderBy and addOrderBy could be used:

$query->orderBy([     'id' => SORT_ASC,     'name' => SORT_DESC, ]);

Here we are ordering by id ascending and then by name descending.

GROUP BY and HAVING

In order to add GROUP BY to generated SQL you can use the following:

$query->groupBy('id, status');

If you want to add another field after using groupBy:

$query->addGroupBy(['created_at', 'updated_at']);

To add a HAVING condition the corresponding having method and its andHaving and orHaving can be used. Parameters for these are similar to the ones for where methods group:

$query->having(['status' => $status]);

LIMIT and OFFSET

To limit result to 10 rows limit can be used:

$query->limit(10);

To skip 100 fist rows use:

$query->offset(100);

JOIN

The JOIN clauses are generated in the Query Builder by using the applicable join method:

  • innerJoin()
  • leftJoin()
  • rightJoin()

This left join selects data from two related tables in one query:

$query->select(['user.name AS author', 'post.title as title'])     ->from('user')     ->leftJoin('post', 'post.user_id = user.id');

In the code, the leftJoin() method's first parameter specifies the table to join to. The second parameter defines the join condition.

If your database application supports other join types, you can use those via the generic join method:

$query->join('FULL OUTER JOIN', 'post', 'post.user_id = user.id');

The first argument is the join type to perform. The second is the table to join to, and the third is the condition.

Like FROM, you may also join with sub-queries. To do so, specify the sub-query as an array which must contain one element. The array value must be a Query object representing the sub-query, while the array key is the alias for the sub-query. For example,

$query->leftJoin(['u' => $subQuery], 'u.id=author_id');

UNION

UNION in SQL adds results of one query to results of another query. Columns returned by both queries should match. In Yii in order to build it you can first form two query objects and then use union method:

$query = new Query(); $query->select("id, category_id as type, name")->from('post')->limit(10);  $anotherQuery = new Query(); $anotherQuery->select('id, type, name')->from('user')->limit(10);  $query->union($anotherQuery);

Batch Query

When working with large amount of data, methods such as [[yii\db\Query::all()]] are not suitable because they require loading all data into the memory. To keep the memory requirement low, Yii provides the so-called batch query support. A batch query makes uses of data cursor and fetches data in batches.

Batch query can be used like the following:

use yii\db\Query;  $query = (new Query())     ->from('user')     ->orderBy('id');  foreach ($query->batch() as $users) {     // $users is an array of 100 or fewer rows from the user table }  // or if you want to iterate the row one by one foreach ($query->each() as $user) {     // $user represents one row of data from the user table }

The method [[yii\db\Query::batch()]] and [[yii\db\Query::each()]] return an [[yii\db\BatchQueryResult]] object which implements the Iterator interface and thus can be used in the foreach construct. During the first iteration, a SQL query is made to the database. Data are since then fetched in batches in the iterations. By default, the batch size is 100, meaning 100 rows of data are being fetched in each batch. You can change the batch size by passing the first parameter to the batch() or each() method.

Compared to the [[yii\db\Query::all()]], the batch query only loads 100 rows of data at a time into the memory. If you process the data and then discard it right away, the batch query can help keep the memory usage under a limit.

If you specify the query result to be indexed by some column via [[yii\db\Query::indexBy()]], the batch query will still keep the proper index. For example,

use yii\db\Query;  $query = (new Query())     ->from('user')     ->indexBy('username');  foreach ($query->batch() as $users) {     // $users is indexed by the "username" column }  foreach ($query->each() as $username => $user) { }
 

Tags: yii, yii2

Yii2 Html组件的默认值

 Yii2 的Html组件越来越觉得容易用了。而且也更方便了,不过设置默认值的时候有一点不方便。比如input的时候都是直接设置placeholder就行了

在Yii1的时候,有一个参数 :htmlOptions => array() , 在Yii2中简化到就剩一个options。。。当然 placeholder 还是可以直接用的

只是在dropdownlist的时候,placeholder就不能用了。这时候的参数是:prompt 

例子:

PHP代码
  1. $form->field($model'lists')->dropDownList(Categories::findAll([1=>1]), ['prompt' => '请选择分类')])  

看到那个findAll([1=>1])没。如果只是用默认的findAll,没有条件的话。不能查询,所以只有1=>1这样。

 

 

uipickerview 学习中遇到的问题点滴

 几个小问题,是在看《精通IOS开发》第六版第七章遇到的

7.8章节:使用自定议选取器创建一个简单游戏

1、P 159 书上写着:添加一个选取器视图,在选取器视图下方添加一个分页

     妹啊,这个分页究竟是什么?开始以为是pagecontrol组件,但看完本章后才发现,这就是一个Label,为什么前后翻译 会不一样??

2、P159最后一段:需要取消选择View设置底部的User Interaction Enabled,这样用户就不能够手动更改刻度盘作弊了

    我擦 ,我把View设置的User Interaction Enabled 的勾取消后,整个页面的button,label什么的全部没有事件了。

    明明只是将pickerview的user interaction enabled的勾取消么,害我浪费了2个小时,我一直在编译、改代码就是想处理为什么我的button不能点击了,点击了之后为什么没反应

3、例程中:

XML/HTML代码
  1. //当然 self.images 是 NSArray  
  2. self.images = @[[UIImage imageNamed:@"seven"] , [UIImage imageNamed:@"apple"]];  

 

但是如果纯粹翻译成swift这是错误的

大小: 36.74 K
尺寸: 500 x 89
浏览: 2180 次
点击打开新窗口浏览全图

最后我改成了:

XML/HTML代码
  1. self.images = ["seven","bar","crown","cherry","lemon","apple"]  

 

然后在调用的时候再创建UIImage,比如:

XML/HTML代码
  1. func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView!) -> UIView {  
  2.       
  3.     var img = self.images?[row] as String ;  
  4.     return  UIImageView(image: UIImage(named: img));  
  5. }  

 

这也算是曲线救国吧,等下次学的深的时候再来看一下这个问题

4、声音

原文中,#import <AudioToolbox/AudioToolbox.h>在swift中就方便了,直接 import AutioToolbox

不过读取声音资源的时候也确实不一样

XML/HTML代码
  1. //.h  
  2. @implementation xxxController{  
  3.     SystemSoundID xxxSoundId  
  4. }  
  5. //.m  
  6. if (xxxSoundId == 0) {  
  7.     NSString *path = [[NSBundle mainBundle] pathForResource:@"xxx" ofType:@"wav"];  
  8.     NSURL *soundURL = [NSURL fileURLWithPath:path];  
  9.     AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL , &xxxSoundId );  
  10. }  
  11. //然后就可以播放了  
  12. AudioServicePlaySystemSound(xxxSoundId);  

 

在swift中就不能这么写了。首先,没看到有(__bridge CFURLRef),经过google,我找到了这里:http://stackoverflow.com/questions/24043904/creating-and-playing-a-sound-in-swift,有很多人回答了,有人说flappyswift中有人这样用:

XML/HTML代码
  1. import SpriteKit  
  2. import AVFoundation  
  3.   
  4. class GameScene: SKScene {  
  5.   
  6.     // Grab the path, make sure to add it to your project!  
  7.     var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("coin", ofType: "wav"))  
  8.     var audioPlayer = AVAudioPlayer()  
  9.   
  10.     // Initial setup  
  11.     override func didMoveToView(view: SKView) {  
  12.         audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)  
  13.         audioPlayer.prepareToPlay()  
  14.     }  
  15.   
  16.     // Trigger the sound effect when the player grabs the coin  
  17.     func didBeginContact(contact: SKPhysicsContact!) {  
  18.         audioPlayer.play()  
  19.     }  
  20.   
  21. }  

 

也有人提了个主意,但是说新版的xcode已经不能用了。最后有人贴了段代码:

XML/HTML代码
  1. import AudioToolbox  
  2.   
  3. let chaChingSound: SystemSoundID = createChaChingSound()  
  4.   
  5. class CashRegisterViewController: UIViewController {  
  6.     override func viewWillAppear(animated: Bool) {  
  7.         super.viewWillAppear(animated)  
  8.         AudioServicesPlaySystemSound(chaChingSound)  
  9.     }  
  10. }  
  11.   
  12. func createChaChingSound() -> SystemSoundID {  
  13.     var soundID: SystemSoundID = 0  
  14.     let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "Cha-Ching", "aiff", nil)  
  15.     AudioServicesCreateSystemSoundID(soundURL, &soundID)  
  16.     CFRelease(soundURL)  //新版xocde已经不要这一句了,提示自动管理内存,不要你主动释放了
  17.     return soundID  
  18. }  

 

嗯,我就是用的这个。

5、[sef performSelector]

标题的这个方法,在swift中已经没有了,那怎么延迟0.5秒呢?stackoverflow上也有答案:http://stackoverflow.com/questions/24170282/swift-performselector-withobject-afterdelay

最简单的就是:

XML/HTML代码
  1. var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)  
  2.   
  3. func someSelector() {  
  4.     // Something after a delay  
  5. }  

 

或者 :

XML/HTML代码
  1. dispatch_after(0.1, dispatch_get_main_queue(), {  
  2.     // your function here  
  3. })  

 

---至此,第7章全部看完。

整个第一章就一个Tabbar和pickerview加datepickerview,却有这么多的问题,而且还有一个就是pickerview中的数据怎么循环?暂时还没有仔细的了解 ,先把整本书读完试试

 

 

swift srand(time(NULL))

随机数在OC中真心简单啊 srand(time(null)),可是这样的代码到了 Swift中就行不通了

首先:swift没有null,time(nil)出来的又是 int,但 srand 的传入参数 又是Uint32.。。所以好让人纠结

不过网上还是有高手,他们说,你可以这样:srand(UInt32(time(nil))),看上去和原来的OC几乎一样,当然 他还提出了

XML/HTML代码
  1. But consider to use arc4random() or its variants instead. From http://nshipster.com/random/:  
  2.   
  3. arc4random does not require an initial seed (with srand or srandom), making it that much easier to use.  
  4. arc4random has a range up to 0x100000000 (4294967296), whereas rand and random top out at RAND_MAX = 0x7fffffff (2147483647).  
  5. rand has often been implemented in a way that regularly cycles low bits, making it more predictable.  
  6. For example,  
  7.   
  8. let x = arc4random_uniform(10)  
  9. generates a random number in the range 0 ... 9.  

 

可是还有人说:

XML/HTML代码
  1. let time = UInt32(NSDate().timeIntervalSinceReferenceDate)  
  2. srand(time)  
  3. print("Random number: \(rand()%10)")  

 

得,还是能用就成

Tags: swift, srand

swift pragma mark

众所周知,大家在OC中对代码进行逻辑组织 用的是#pragma mark - ,生成分隔线

用#pragma mark 函数说明,来生成一个函数的说明X
但在swift中,这个语法就不支持了,毕竟它是属于C的语法,于是就有了新的一些语法,如:// MARK: // FIXME // TODO: 等
 
// MARK: - 生成分隔线
// MARK: 说明
别忘了那个冒号。。。
 
参考 :http://stackoverflow.com/questions/24017316/pragma-mark-in-swift

Tags: swift, pragma