Revision #17 has been created by softark on Sep 29, 2018, 11:16:18 PM with the memo:
Fixed a markup
« previous (#16) next (#18) »
Changes
Title
unchanged
Drills : Search by a HAS_MANY relation in Yii 1.1
Category
unchanged
Tutorials
Yii version
changed
1.1
Tags
changed
search,has_many, search, CActiveRecord
Content
changed
[...]
## Example of HAS_MANY
Think about blog posts and their authors. It's a relation of "An Author has many Posts" and "A Post belongs to an Author" at the same time.
```php
/**
* Author model[...]
```
```php
/**
* Post model[...]
I want to start with an easy one. Let's retrieve all the posts that has a cirtain word in their title.
```php
public static function GetPostsByTitle($searchWord)
{[...]
Now we have to retrieve the authors' name, too.
```php
public static function GetPostsWithAuthorByTitle($searchWord)
{[...]
So you can write like this when you want to search by Author's name.
```php
...
// compare Author's name[...]
Now we will retrieve the authors, not the posts.
```php
public static function GetAuthorsByPostTitle($searchWord)
{[...]
### Wrong Answer
```php
public static function GetAuthorsWithPostsByPostTitle($searchWord)
{[...]
### Answer
```php
public static function GetAuthorsWithPostsByPostTitle($searchWord)
{[...]
### Trial #1
```php
public static function GetTop5AuthorsWithPostsByPostTitle($searchWord)
{[...]
### Trial #2
```php
...
// force to join Post[...]
But, alas, you will get the strange output like this:
~~~```
[search word = foo]
Author = Andy[...]
Post = What's foo?
[end]
~~~```
We want to show 5 authors, but the list ends where the count of posts sums up to 5.[...]
### Trial #3
```php
...
// force to join Post (without selecting)[...]
### Trial #4
```php
...
// force to join Post (without selecting)[...]
### Answer
```php
public static function GetTop5AuthorsWithPostsByPostTitle($searchWord)
{[...]
### Example of Answer
```php
public static function GetTop5AuthorsWithPostsByPostTitle($searchWord)
{[...]
### Optimized Answer to Task #4
```php
public function relations()
{[...]
### Optimized Answer to Task #5
```php
public static function GetTop5AuthorsWithPostsByPostTitle($searchWord)
{[...]
### Optimized Answer to Task #6
```php
public static function GetTop5AuthorsWithPostsByPostTitle($searchWord)
{
// query criteria
$criteria = new CDbCriteria();
// join Post model (one for fetching data, the other for filtering)[...]