How yii2 uses the database (2) using ActiveRecord

In the previous section, we talked about the method of the CreatCommand database, and also talked about the advantages and disadvantages of this method. In this section, we will talk about the above two methods that are more useful.

what are they?

ActiveRecord and QueryBulider are based on the DAO layer and are more enhanced and commonly used database access methods.

ActiveRecord introduction and usage

Active Record

Active Record (active record, hereinafter referred to as AR) provides an object-oriented interface to access data in the database.
* An AR class closes a data table, and each AR object corresponds to a row in the table.
* The attributes of the AR object, corresponding to the columns of the data row
* You can directly manipulate the data in the data table in an object-oriented way, so that you can access
the .

We will introduce these below

Declare the ActiveRecord class

Declare an AR class by inheriting the yii\db\ActiveRecord base class, and implement the tableName method to return the name of the data table associated with it.
This creates an AR class about table

Such as:

class Article extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'article';
    }
    ……

Query data with AR class

AR provides two static methods to construct DB query, fill the queried data into AR object instance, and finally return the object.

yii\db\ActiveRecord::find()


 $model = ArticleStatus::find()->where(['id'=>1])->one();

The where method followed by find, its parameter is the query condition id=1, according to the query condition, it should get the first record in the table, the one method will actually execute the query, and fill an AR class with the query result instance object. This object is the return value. We use the variable model to save it. This is an ActiveRecord object corresponding to the record with id=1 in the database table.

can be abbreviated as

$model = ArticleStatus::findOne(1)
$model = ArticleStatus::findAll(['status'=>2])

Similarly, we can see in the class reference manual that the
find() method implements the ActiveQueryinterface interface. Let's see what this interface actually has.

Creates an yii\db\ActiveQueryInterface instance for query purpose.

I probably categorized it

method name use
all() 、 one() Execute the query statement and return the query result AR object
where()、orwhere()、andwhere() Query conditions
orderBy(),addOrderBy() sort
count() Returns the number of records that match the query criteria
limit() Remove the number of items in the query structure
with() Specify the fields of the associated table

yii\db\ActiveRecord::findBySql()

Query with sql statement. Unlike CreateCommand(), it returns an AR object.

Access column data after getting AR class

  1. AR object when querying a single object
$model = article::findOne(1);

echo $model -> id;
  1. query multiple data

mistake:

$model = article::findAll(['status'=>2);

foreach($model as $item)
{
    echo $item->id;
}

Our method above is to use ordinary methods to store a large amount of input such as (100,000) in objects, which is undoubtedly a waste of space. So the above method should be discarded;

correct:

①If we want to get a lot of data and use objects to store it, it is undoubtedly a waste of memory. We should convert the objects into arrays because the resources occupied by arrays are much smaller than that of objects.

$model = User::find()->where(['status'=>1])->asArray()->all();
        foreach($model as $item)
        {
            echo $item['id']; 
        }

② We should also pay attention when fetching a large amount of data, we can fetch part by part, but not all

 foreach(User::find()->batch(2) as $item)   //一次取出两条数据出来存放到item里
        {
            ……//对两条数据进行操作
        }

Manipulate data CRUD

The AR class provides the following methods to implement CRUD operations

method name
yii\db\ActiveRecord::insert()
yii\db\ActiveRecord::delete()
yii\db\ActiveRecord::update()
yii\db\ActiveRecord::save()

1. Create

$article = new Article();
$article->title = '测试';
$article->content = '测试内容';
$article->save();  //等同于insert()
  1. Read
$article = Article::findOne(1);
  1. Update
$article = Article::findOne(1);
$article->title = "测试1";
$article->save(); //等同于update()
  1. delight
$article = Article::findOne(1);
$article -> delect();

Querying Linked Data with ActiveRecord

When we operate the database, we often encounter situations that require joint table queries. At this time, we need to use ActiveRecord's associated query method

write association

First of all, we need to write the association relationship in the controller. For example, if I want to query the table of articles, there is an author id in it, and I need to query the corresponding author name by linking the table.

Then we need to use the hasone or hasmany method in the models file.

As above:

An article belongs to an author and belongs to one to one, so use the hasone() method in the model of the article

If an author has multiple articles, you need to use the hasmany() method

example:

  public function getAuthor()
    {
        return $this->hasOne(Admin::className(), ['id' => 'author_id']);
    }

When we enter Arcticle-> in the controller

graph LR
Admin::className-->提取出Admin这个模型类的表名

Get the value we need from the AR object

Then the author name we need will be loaded into our AR object.

echo $model->author->username;

to get our value

There are more AR class operations can go to the ActiveQueryInterface class reference manual

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324606737&siteId=291194637