activerecord模式里的attributes属性不管怎么样都是null

yii之ActiveRecord的一些用法 - 郑星阳 - ITeye技术网站
博客分类:
作者:zccst
Yii的ActiveRecord是与数据库打交道的类,也即MVC中的M(模型层),也是ORM的O(Object)。
里面水很深,还有很多不知道的特性,今天列举一二,以后慢慢补充
1,对象转数组
$model = new ActiveRecord();
$model.toArray();
由于ActiveRecord不是简单数组,不能直接json_encode,否则信息不完整。
解决办法:$model.toArray();这样就变为简单数组了,可以进行json_encode了。
2,通过名字或其他字段直接获取ActiveRecord的id。
$nIdcId = idc_info::model()-&find('name like :name',array(':name'=&"%".$strIdcName."%"))-&
我以前经常使用的办法是(现在发现很土):
$idc = Idc::model()-&find("...");
$id& = $idc-&
3,对model的理解
$accModel = call_user_func(array(ActiveRecordName, 'model'));
$model&&& = $accModel-&findByPk($id);
如果您觉得本文的内容对您的学习有所帮助,您可以微信:
//没这个方法,我来加一个吧//ActiveRecord转成Array&&& private function toArray($activeRecord){&&&&&&& $dataset = array();&&&&&&& $i = 0;&&&&&&& foreach($activeRecord as $t)&&&&&&& {&&&&&&&&&&& $dataset[$i] = $t-&&&&&&&&&&&& $i++;&&&&&&& }&&&&&&& return $&&& }
浏览: 1741005 次
来自: 北京
谢谢,虽然不能给你赞助,但是要给你顶
阿凡达阿凡达阿凡达阿凡达阿凡达阿凡达阿凡达阿凡达阿凡达阿滕庆亚 ...
用过SpreadJS,也包含数据可视化的图表
不知道为什么,我尝试用标签引入没有效果,而通过 preload ...
seajs 和 requirejs最大的区别是执行阶段。相同点 ...Declares the name of the Mongo collection associated with this AR class.
Collection name can be either a string or array:
if string considered as the name of the collection inside the default database.
if array - first element considered as the name of the database, second - as
name of collection inside that database
By default this method returns the class name as the collection name by calling .
For example, 'Customer' becomes 'customer', and 'OrderItem' becomes
'order_item'. You may override this method if the collection is not named after this convention.
public static |
The collection name
Deletes the document corresponding to this active record from the collection.
This method performs the following steps in order:
call . If the method returns false, it will skip the
delete the document
In the above step 1 and 3, events named
will be raised by the corresponding methods.
The number of documents deleted, or false if the deletion is unsuccessful for some reason.
Note that it is possible the number of documents deleted is 0, even though the deletion execution is successful.
is enabled and the data
being deleted is outdated.
in case delete failed.
Deletes documents in the collection using the provided conditions.
WARNING: If you do not specify any condition, this method will delete documents rows in the collection.
For example, to delete all customers whose status is 3:
Customer::deleteAll(['status' =& 3]);
public static
( $condition&=&[], $options&=&[] )
$condition
Description of the objects to delete.
Please refer to
on how to specify this parameter.
List of options in format: optionName =& optionValue.
The number of documents deleted.
See also .
protected void
Returns a value indicating whether the given active record is the same as the current one.
The comparison is made by comparing the collection names and the primary key values of the two active records.
If one of the records
they are also considered not equal.
( $record )
Record to compare to
Whether the two active records refer to the same row in the same Mongo collection.
Creates an \yii\mongodb\ActiveQueryInterface instance for query purpose.
The returned \yii\mongodb\ActiveQueryInterface instance can be further customized by calling
methods defined in \yii\mongodb\ActiveQueryInterface before one() or all() is called to return
populated ActiveRecord instances. For example,
$customer = Customer::find()-&where(['id' =& 1])-&one();
$customers = Customer::find()
-&where(['status' =& 1])
-&orderBy('age')
This method is also called by
create a relational query.
You may override this method to return a customized query. For example,
class Customer extends ActiveRecord
public static function find()
return new CustomerQuery(get_called_class());
The following code shows how to apply a default condition for all queries:
class Customer extends ActiveRecord
public static function find()
return parent::find()-&where(['deleted' =& false]);
$customers = Customer::find()-&andWhere('age&30')-&all();
$customers = Customer::find()-&where('age&30')-&all();
public static
The newly created
Return the Mongo collection instance for this AR class.
public static
Collection instance.
Returns the Mongo connection used by this AR class.
By default, the "mongodb" application component is used as the Mongo connection.
You may override this method if you want to use a different database connection.
public static
The database connection used by this AR class.
Inserts a row into the associated Mongo collection using the attribute values of this record.
This method performs the following steps in order:
when $runValidation is true. If validation
fails, it will skip t
when $runValidation is true.
call . If the method returns false, it will skip the
insert the record into collection. If this fails, it will skip t
In the above step 1, 2, 3 and 5, events ,
will be raised by the corresponding methods.
will be inserted into database.
If the primary key
is null during insertion, it will be populated with the actual
value after insertion.
For example, to insert a customer record:
$customer = new Customer();
$customer-&name = $name;
$customer-&email = $email;
$customer-&insert();
( $runValidation&=&true, $attributes&=&null )
$runValidation
Whether to perform validation before saving the record.
If the validation fails, the record will not be inserted into the collection.
$attributes
List of attributes that need to be saved. Defaults to null,
meaning all attributes that are loaded will be saved.
Whether the attributes are valid and the record is inserted successfully.
in case insert failed.
See also .
protected void
( $attributes&=&null )
$attributes
Returns the primary key name(s) for this AR class.
The default implementation will return ['_id'].
Note that an array should be returned even for a collection with single primary key.
public static []
The primary keys of the associated Mongo collection.
Converts the model into an array.
This method will first identify which fields to be included in the resulting array by calling .
It will then turn the model into an array with these fields. If $recursive is true,
any embedded objects will also be converted into arrays.
If the model implements the \yii\mongodb\Linkable interface, the resulting array will also have a _link element
which refers to a list of links as specified by the interface.
$fields&=&[],
$expand&=&[], $recursive&=&true )
The fields being requested. If empty, all fields as specified by
will be returned.
The additional fields being requested for exporting. Only fields declared in
will be considered.
$recursive
Whether to recursively return array representation of embedded objects.
The array representation of the object
Updates all documents in the collection using the provided attribute values and conditions.
For example, to change the status to be 1 for all customers whose status is 2:
Customer::updateAll(['status' =& 1], ['status' =& 2]);
public static
( $attributes, $condition&=&[], $options&=&[] )
$attributes
Attribute values (name-value pairs) to be saved into the collection
$condition
Description of the objects to update.
Please refer to
on how to specify this parameter.
List of options in format: optionName =& optionValue.
The number of documents updated.
Updates all documents in the collection using the provided counter changes and conditions.
For example, to increment all customers' age by 1,
Customer::updateAllCounters(['age' =& 1]);
public static
( $counters, $condition&=&[], $options&=&[] )
The counters to be updated (attribute name =& increment value).
Use negative values if you want to decrement the counters.
$condition
Description of the objects to update.
Please refer to
on how to specify this parameter.
List of options in format: optionName =& optionValue.
The number of documents updated.
See also .
protected void
( $attributes&=&null )
$attributes摘要:最近几天有时间看了一下Castle,原来它的功能是如此的强大,从数据访问框架到IOC容器,再到WEB框架,基本包括了整个开发过程中的所有东西,看来得好好学习研究一下了,并且打算把自己学习过程的一些东西记录下来。先从ActiveRecord开始吧,ActiveRecord提供的简洁的O/R映射给我留下了很深的印象,本文将通过一个简单对象的CRUD操作来带你快速走进Castle ActiveRecord。
2.准备相关的数据表
3.编写User实体类
4.构建配置信息
5.开始CRUD操作
6.使用ActiveRecord Generator生成实体类代码
如果你用过NHibernate,一定会对在NHibernate中编写.hbm.xml文件印象深刻,我也是。而在Castle ActiveRecord中,我们不用再为编写繁冗复杂的映射文件而头疼,ActiveRecord是Castle中提供的一个数据访问框架,它在底层封装了NHibernate的操作,使用特性来代替映射文件,它提供的简洁的O/R映射会让你惊叹原来实现持久化数据层是那么简单。下面我们通过一个简单对象的CRUD操作来快速进入Castle ActiveRecord。
二.准备相关的数据表
假定数据库中有这样一张用户表,用来保存用户的信息,如下
CREATE&TABLE&[dbo].[Users]&(&&&&[LogonID]&[int]&IDENTITY&(<span style="FONT-WEIGHT: COLOR: #,&<span style="FONT-WEIGHT: COLOR: #)&NOT&NULL&,&&&&[LogonName]&[varchar]&(<span style="FONT-WEIGHT: COLOR: #)&COLLATE&Chinese_PRC_CI_AS&NULL&,&&&&[Password]&[varchar]&(<span style="FONT-WEIGHT: COLOR: #)&COLLATE&Chinese_PRC_CI_AS&NULL&,&&&&[EmailAddress]&[varchar]&(<span style="FONT-WEIGHT: COLOR: #)&COLLATE&Chinese_PRC_CI_AS&NULL&,&&&&[LastLogon]&[datetime]&NULL&)&ON&[PRIMARY]GO
三.编写User实体类
首先我们新建一个User类并让它继承于ActiveRecordBase类
public&class&User&:&ActiveRecordBase{&&&&//}
为User类添加特性,其实就是告诉ActiveRecord,User类所对应的数据库中的数据表名为Users
[ActiveRecord("Users")]public&class&User&:&ActiveRecordBase{&&&&//}
下面我们的工作就是为实体类添加属性
[ActiveRecord("Users")]public&class&User&:&ActiveRecordBase{&&&&private&int&_&&&&private&string&_&&&&private&string&_&&&&private&string&_emailA&&&&private&DateTime&_lastL&&&&[PrimaryKey(PrimaryKeyType.Identity,&"LogonID")]&&&&public&int&Id&&&&{&&&&&&&&get&{&return&_&}&&&&&&&&set&{&_id&=&&}&&&&}&&&&&&&&[Property("LogonName")]&&&&public&string&Name&&&&{&&&&&&&&get&{&return&_&}&&&&&&&&set&{&_name&=&&}&&&&}&&&&&&&&[Property("Password")]&&&&public&string&Password&&&&{&&&&&&&&get&{&return&_&}&&&&&&&&set&{&_password&=&&}&&&&}&&&&&&&&[Property("EmailAddress")]&&&&public&string&Address&&&&{&&&&&&&&get&{&return&_emailA&}&&&&&&&&set&{&_emailAddress&=&&}&&&&}&&&&&&&&[Property("LastLogon")]&&&&public&DateTime&LastLogon&&&&{&&&&&&&&get&{&return&_lastL&}&&&&&&&&set&{_lastLogon&=&&}&&&&}}
大家可能注意到了,每一个属性上面都加上了特性[Property()]。简单的说明一下,这里用[PrimaryKey]特性指定Id作为主键,并且说明了主键的类型为自增型的,用PrimaryKeyType.Identity来说明,在后续文章中我会详细说明的。如果属性名和字段名一致,[Property()]中可以为空,也可以写上字段的名字。
下一步我们为实体类根据需要加上静态的操作方法,至于Create(),Update(),Delete(),Save()等方法则会直接从ActiveRecordBase基类中继承
[ActiveRecord("Users")]public&class&User&:&ActiveRecordBase{&&&&//&#8230;&#8230;&&&&public&static&void&DeleteAll()&&&&{&&&&&&&&DeleteAll(&typeof(User)&);&&&&}&&&&public&static&IList&FindAll()&&&&{&&&&&&&&return&(IList)&FindAll(&typeof(User)&);&&&&}&&&&public&static&User&Find(int&id)&&&&{&&&&&&&&return&(User)&FindByPrimaryKey(&typeof(User),&id&);&&&&}}
整个完成后的实体类代码
using&Susing&System.Cusing&Castle.ActiveRnamespace&ARDemo{&&&&/**////&&summary&&&&&///&User&的摘要说明。&&&&///&&/summary&&&&&[ActiveRecord("Users")]&&&&public&class&User&:&ActiveRecordBase&&&&{&&&&&&&&private&int&_&&&&&&&&private&string&_&&&&&&&&private&string&_&&&&&&&&private&string&_emailA&&&&&&&&private&DateTime&_lastL&&&&&&&&[PrimaryKey(PrimaryKeyType.Identity,&"LogonID")]&&&&&&&&public&int&Id&&&&&&&&{&&&&&&&&&&&&get&{&return&_&}&&&&&&&&&&&&set&{&_id&=&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property("LogonName")]&&&&&&&&public&string&Name&&&&&&&&{&&&&&&&&&&&&get&{&return&_&}&&&&&&&&&&&&set&{&_name&=&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property("Password")]&&&&&&&&public&string&Password&&&&&&&&{&&&&&&&&&&&&get&{&return&_&}&&&&&&&&&&&&set&{&_password&=&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property("EmailAddress")]&&&&&&&&public&string&Address&&&&&&&&{&&&&&&&&&&&&get&{&return&_emailA&}&&&&&&&&&&&&set&{&_emailAddress&=&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property("LastLogon")]&&&&&&&&public&DateTime&LastLogon&&&&&&&&{&&&&&&&&&&&&get&{&return&_lastL&}&&&&&&&&&&&&set&{_lastLogon&=&&}&&&&&&&&}&&&&&&&&public&static&void&DeleteAll()&&&&&&&&{&&&&&&&&&&&&DeleteAll(&typeof(User)&);&&&&&&&&}&&&&&&&&public&static&IList&FindAll()&&&&&&&&{&&&&&&&&&&&&return&(IList)&FindAll(&typeof(User)&);&&&&&&&&}&&&&&&&&public&static&User&Find(int&id)&&&&&&&&{&&&&&&&&&&&&return&(User)&FindByPrimaryKey(&typeof(User),&id&);&&&&&&&&}&&&&}}
四.构建配置信息
现在我们要告诉ActiveRecord相关的数据库、数据驱动等信息,最简单的就是使用配置文件
&?xml&version="1.0"&encoding="utf-8"&?&&configuration&&&&&&configSections&&&&&&&&&&section&name="activerecord"&type="Castle.ActiveRecord.Framework.Config.ActiveRecordSectionHandler,&Castle.ActiveRecord"&/&&&&&&/configSections&&&&&&activerecord&&&&&&&&&&config&&&&&&&&&&&&&&add&key="hibernate.connection.driver_class"&value="NHibernate.Driver.SqlClientDriver"&/&&&&&&&&&&&&&&add&key="hibernate.dialect"&value="NHibernate.Dialect.MsSql2000Dialect"&/&&&&&&&&&&&&&&add&key="hibernate.connection.provider"&value="NHibernate.Connection.DriverConnectionProvider"&/&&&&&&&&&&&&&&add&key="hibernate.connection.connection_string"&value="UID=Password=Initial&Catalog=ARDData&Source=."&/&&&&&&&&&&/config&&&&&&/activerecord&&/configuration&
用过NHibernate的朋友一定会对这段配置代码很熟悉,没错,因为ActiveRecord在底层封装了NHibernate,所以这里的配置跟使用NHibernate时的配置一样,同样是指定了数据源驱动,连接字符串等信息。如果使用了配置文件在代码中只要这样去初始化就可以了
IConfigurationSource&source&=&System.Configuration.ConfigurationSettings.GetConfig("activerecord")&as&IConfigurationSActiveRecordStarter.Initialize(&source,&typeof(User)&);
我们也可以不使用配置文件,而使用代码指定的方式,但是由于这种方式相当于硬编码了,不大推荐大家使用这种方式:
InPlaceConfigurationSource&source&=&new&InPlaceConfigurationSource();Hashtable&properties&=&new&Hashtable();properties.Add("hibernate.connection.driver_class",&"NHibernate.Driver.SqlClientDriver");properties.Add("hibernate.dialect",&"NHibernate.Dialect.MsSql2000Dialect");properties.Add("hibernate.connection.provider",&"NHibernate.Connection.DriverConnectionProvider");properties.Add("hibernate.connection.connection_string",&"UID=Password=;Initial&Catalog=ARDData&Source=.");source.Add(&typeof(ActiveRecordBase),&properties&);ActiveRecordStarter.Initialize(&source,&typeof(User)&);
五.开始CRUD操作
好了,经过了前面的步骤之后,就可以正式开始我们的对象CRUD操作了。
1.增加User对象
[Test]public&void&AddUser(){&&&&User&user&=&new&User();&&&&user.Name&=&"Terrylee";&&&&user.Password&=&"aaa";&&&&user.Address&=&"lhj_";&&&&user.LastLogon&=&DateTime.N&&&&&&&&user.Create();}
是不是非常简单?我们甚至都没有写过Create()方法,它直接从ActiveRecordBase类继承。我们所做的只是创建这样一个User对象,然后调用它的方法就可以了。
2.查询所有的User对象
[Test]public&void&FildAll(){&&&&IList&list&=&User.FindAll();&&&&Assert.IsNotNull(list);&&&&int&actual&=&list.C&&&&int&expected&=&<span style="COLOR: #;&&&&Assert.AreEqual(expected,actual);}
3.查询某一个指定Id的User对象
[Test]public&void&Fild(){&&&&int&id&=&<span style="COLOR: #;&&&&User&actual&=&User.Find(id);&&&&Assert.IsNotNull(actual);&&&&Assert.AreEqual("Terrylee",actual.Name);&&&&Assert.AreEqual("aaa",actual.Password);}
4.修改User对象
[Test]public&void&UpdateUser(){&&&&User&user&=&new&User();&&&&user.Id&=&<span style="COLOR: #;&&&&user.Name&=&"Aero";&&&&user.Password&=&"aaa";&&&&user.Address&=&"";&&&&user.LastLogon&=&DateTime.N&&&&user.Update();}
5.删除User对象
[Test]public&void&DeleteUser(){&&&&User&user&=&new&User();&&&&user.Id&=&<span style="COLOR: #;&&&&user.Delete();}
6.删除所有的User对象
[Test]public&void&DeleteAll(){&&&&User.DeleteAll();}
可以看到,整个过程非常的简洁简单,没有一点多余复杂的代码,相信你已经开始体会到了ActiveRecord的魅力了。唯一有一点你会感到不舒服的是已经有了数据库表还需要手工编写实体类代码,这个不用担心,ActiveRecord已经为我们提供了代码生成工具ActiveRecord Generator。
六.使用ActiveRecord Generator生成实体类代码
1.执行Castle.ActiveRecord.Generator.exe,位于目录C:\Program Files\Castle\Bin\net-1.1\下面,可以看到如下界面,选择Project Explorer面板
2.点击&#8220;Add DataBase Connection&#8221;图标,如下图中红色方框所示,弹出设置连接字符串对话框,我们首先要为数据库起一个别名,这个名字可以跟数据库名不一样,在后面我们会用到
注意:如果连接数据库为SQL Server2000数据库,必须在弹出的对话框中选中允许保存密码选项,否则点击OK按钮时会报登录失败的错误!这点不知道是不是我机器的设置问题,如果有朋友遇到这样的错误,不妨一试。
3.点击OK后,选择ActiveRecord Components面板
4.拖动ActiveRecord到左边的空白区域,会出现如下界面,选择我们刚才设置的数据库别名
5.此后操作有选择子段,设置类名等,全部完成后界面如下:
6.选择Project菜单下的Generate Code,输入命名空间,文件设置路径,并选择所要生成代码语言
注意:有一个选项是否覆盖已经存在的文件,可以根据自己的实际情况选择
7.最后生成的完整实体类代码如下
//&//&Generated&by&ActiveRecord&Generator//&//namespace&ARDemo{&&&&using&Castle.ActiveR&&&&&&&&&&&&[ActiveRecord("Users")]&&&&public&class&User&:&ActiveRecordBase&&&&{&&&&&&&&&&&&&&&&private&int&_logonID;&&&&&&&&&&&&&&&&private&string&_logonN&&&&&&&&&&&&&&&&private&string&_&&&&&&&&&&&&&&&&private&string&_emailA&&&&&&&&&&&&&&&&private&System.DateTime&_lastL&&&&&&&&&&&&&&&&[PrimaryKey(PrimaryKeyType.Native)]&&&&&&&&public&int&LogonID&&&&&&&&{&&&&&&&&&&&&get&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return&this._logonID;&&&&&&&&&&&&}&&&&&&&&&&&&set&&&&&&&&&&&&{&&&&&&&&&&&&&&&&this._logonID&=&&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property()]&&&&&&&&public&string&LogonName&&&&&&&&{&&&&&&&&&&&&get&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return&this._logonN&&&&&&&&&&&&}&&&&&&&&&&&&set&&&&&&&&&&&&{&&&&&&&&&&&&&&&&this._logonName&=&&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property()]&&&&&&&&public&string&Password&&&&&&&&{&&&&&&&&&&&&get&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return&this._&&&&&&&&&&&&}&&&&&&&&&&&&set&&&&&&&&&&&&{&&&&&&&&&&&&&&&&this._password&=&&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property()]&&&&&&&&public&string&EmailAddress&&&&&&&&{&&&&&&&&&&&&get&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return&this._emailA&&&&&&&&&&&&}&&&&&&&&&&&&set&&&&&&&&&&&&{&&&&&&&&&&&&&&&&this._emailAddress&=&&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&&&&&&&&[Property()]&&&&&&&&public&System.DateTime&LastLogon&&&&&&&&{&&&&&&&&&&&&get&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return&this._lastL&&&&&&&&&&&&}&&&&&&&&&&&&set&&&&&&&&&&&&{&&&&&&&&&&&&&&&&this._lastLogon&=&&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&&&&&&&&public&static&void&DeleteAll()&&&&&&&&{&&&&&&&&&&&&ActiveRecordBase.DeleteAll(typeof(User));&&&&&&&&}&&&&&&&&&&&&&&&&public&static&User[]&FindAll()&&&&&&&&{&&&&&&&&&&&&return&((User[])(ActiveRecordBase.FindAll(typeof(User))));&&&&&&&&}&&&&}}
大家还应该注意的一点是生成One-Many/Many-One等关系的实体类文件时可能会出现一些问题,需要对生成的代码手工改动。最后希望和研究Castle的朋友能够多多交流!
Castle的官方网站
阅读(...) 评论()

我要回帖

更多关于 ruby activerecord 的文章

 

随机推荐