Home php教程 php手册 Yii framwork crud 命名范围NAMED SCOPE

Yii framwork crud 命名范围NAMED SCOPE

Jun 13, 2016 am 10:55 AM
1 crud Note yii name right support Version of scope

命名范围
Note: 对命名范围的支持从版本 1.0.5 开始。 命名范围的最初想法来源于 Ruby on Rails.
命名范围(named scope) 表示一个 命名的(named)查询规则,它可以和其他命名范围联合使用并应用于 Active Record 查询
命名范围主要是在 CActiveRecord::scopes() 方法中以名字-规则对的方式声明。如下代码在 Post 模型类中声明了两个命名范围,
published 和 recently。
class Post extends CActiveRecord
{
    ......
    public function scopes()
    {
        return array(
            'published'=>array(
                'condition'=>'status=1',
            ),
            'recently'=>array(
                'order'=>'create_time DESC',
                'limit'=>5,
            ),
        );
    }
}
具体使用:  $posts=Post::model()->published()->recently()->findAll();
注意: 命名范围只能用于类级别方法。也就是说,此方法必须使用 ClassName::model() 调用。

参数化的命名范围
命名范围可以参数化。例如, 我们想自定义 recently 命名范围中指定的帖子数量,要实现此目的,不是在CActiveRecord::scopes
方法中声明命名范围, 而是需要定义一个名字和此命名范围的名字相同的方法:
public function recently($limit=5)
{
    $this->getDbCriteria()->mergeWith(array(
        'order'=>'create_time DESC',
        'limit'=>$limit,
    ));
    return $this;
}
然后,我们就可以使用如下语句获取3条最近发布的帖子。
$posts=Post::model()->published()->recently(3)->findAll();//上面的代码中,默认获取 5 条最近发布的帖子。

默认范围
模型类可以有一个默认范围,它将应用于所有 (包括相关的那些) 关于此模型的查询。例如,一个支持多种语言的网站可能只想显
示当前用户所指定的语言的内容。 因为可能会有很多关于此网站内容的查询, 我们可以定义一个默认范围以解决此问题。 为实
现此目的,我们覆盖 CActiveRecord::defaultScope 方法如下:
class Content extends CActiveRecord
{
    public function defaultScope()
    {
        return array(
            'condition'=>"language='".Yii::app()->language."'",
        );
    }
}

现在,如果下面的方法被调用,将会自动使用上面定义的查询规则:$contents=Content::model()->findAll();

 


实际应用
上面的是几个官方给出的例子,下面是我自己使用的例子供大家参考一下:

TABLE:
school:id(pk,int),name(varchar)  //学校
class:id(pk,int),name(varchar),s_id(fk,int)  //班级
student:id(pk,int),name(varchar),s_id(int),c_id(int)  //学生

例子:查询为学校为“a"的,所有班级,这时我们可以先在School模型中的relations方法中定义一个关系方便调用
public function relations() 

    return array( 
        'class'=>array(self::HAS_MANY, 'Class', 's_id'), 
    ); 
}
public function scopes()
{
    return array(
        'getAllClass'=>array(
            'with'=>'class',
        ),
    };
}
public function getAllClass($name)
{
    $this->getDbCriteria()->mergeWith(array(
        'condition'=>"t.name=$name",
    ));
    return $this;

}

使用:School::model()->getAllClass("a")->findAll();

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

Simple steps to update pip version: done in 1 minute Simple steps to update pip version: done in 1 minute Jan 27, 2024 am 09:45 AM

Done in one minute: How to update the pip version, specific code examples are required. With the rapid development of Python, pip has become a standard tool for Python package management. However, as time goes by, pip versions are constantly updated. In order to be able to use the latest features and fix possible security vulnerabilities, it is very important to update the pip version. This article will explain how to quickly update pip in one minute and provide specific code examples. First, we need to open a command line window. In Windows systems, you can use

Check the Kirin operating system version and kernel version Check the Kirin operating system version and kernel version Feb 21, 2024 pm 07:04 PM

Checking the Kylin operating system version and kernel version In the Kirin operating system, knowing how to check the system version and kernel version is the basis for system management and maintenance. Method 1 to check the Kylin operating system version: Use the /etc/.kyinfo file. To check the Kylin operating system version, you can check the /etc/.kyinfo file. This file contains operating system version information. Execute the following command: cat/etc/.kyinfo This command will display detailed version information of the operating system. Method 2: Use the /etc/issue file Another way to check the operating system version is by looking at the /etc/issue file. This file also provides version information, but may not be as good as the .kyinfo file

Interpret the meaning and difference of PHP version NTS Interpret the meaning and difference of PHP version NTS Mar 27, 2024 am 11:48 AM

The meaning and difference of PHP version NTS PHP is a popular server-side scripting language that is widely used in the field of web development. There are two main versions of PHP: ThreadSafe(TS) and Non-ThreadSafe(NTS). On the official website of PHP, we can see two different PHP download versions, namely PHPNTS and PHPTS. So, what does PHP version NTS mean? What is the difference between it and the TS version? Next,

How to easily check the installed version of Oracle How to easily check the installed version of Oracle Mar 07, 2024 am 11:27 AM

How to easily check the installed version of Oracle requires specific code examples. As a software widely used in enterprise-level database management systems, the Oracle database has many versions and different installation methods. In our daily work, we often need to check the installed version of the Oracle database for corresponding operations and maintenance. This article will introduce how to easily check the installed version of Oracle and give specific code examples. Method 1: Through SQL query in the Oracle database, we can

750,000 rounds of one-on-one battle between large models, GPT-4 won the championship, and Llama 3 ranked fifth 750,000 rounds of one-on-one battle between large models, GPT-4 won the championship, and Llama 3 ranked fifth Apr 23, 2024 pm 03:28 PM

Regarding Llama3, new test results have been released - the large model evaluation community LMSYS released a large model ranking list. Llama3 ranked fifth, and tied for first place with GPT-4 in the English category. The picture is different from other benchmarks. This list is based on one-on-one battles between models, and the evaluators from all over the network make their own propositions and scores. In the end, Llama3 ranked fifth on the list, followed by three different versions of GPT-4 and Claude3 Super Cup Opus. In the English single list, Llama3 overtook Claude and tied with GPT-4. Regarding this result, Meta’s chief scientist LeCun was very happy and forwarded the tweet and

How to easily install Python on Windows, you can choose from two methods How to easily install Python on Windows, you can choose from two methods Feb 18, 2024 pm 04:57 PM

Why is Python so popular? The reason is simple: it is easy to learn, easy to use, and quick to use, making it suitable for beginners. No matter what the project is, as long as it involves programming, Python is often my first choice. Moreover, you don’t have to stick to Linux systems, Windows can also support it well. I have Python installed on my Windows 11 operating system and I often use it to write programs and run code. Installing Python on Windows is very simple, and next I will share two common installation methods. Choose the appropriate Python version. Python provides multiple versions. It is very important to choose the appropriate version. This is related to the compatibility and functionality of the program: the current versions include Python2 and

Does PyCharm Community Edition support enough plugins? Does PyCharm Community Edition support enough plugins? Feb 20, 2024 pm 04:42 PM

Does PyCharm Community Edition support enough plugins? Need specific code examples As the Python language becomes more and more widely used in the field of software development, PyCharm, as a professional Python integrated development environment (IDE), is favored by developers. PyCharm is divided into two versions: professional version and community version. The community version is provided for free, but its plug-in support is limited compared to the professional version. So the question is, does PyCharm Community Edition support enough plug-ins? This article will use specific code examples to

See all articles