Yii scope related models

397 views Asked by At

I have Page model which HAS_MANY Attachment In Page model:

public function relations()
{
    return array(
        'attachments'=>array(self::HAS_MANY, 'Attachment', 'parent_id'),
    )
}

and I am looking for a way to do some scoping on these attachments.

In the PageController I have:

    $model = Page::model()->with(array('attachments'))->findByAttributes(array('slug' => $slug))

For example in the Page view I would like to:

  • get all attachments: $model->attachments (this works fine), but also I need:
  • get all published attachments (all with status = 1)
  • get first promoted attachment (the first one with promoted = 1)
  • get only the images (mime_type in_array 'image/jpeg', 'image/gif', ...)
  • get all other files (everything that is not an image)

and any combination of them. Ex: the first promoted and published image

I guess that the best option is to do it without any extra queries and just filter the $model->attachments , but is it possible?

Edit:

there is one pages table and another attachments table

in the attachments table I have: id, parent_id, file_name, mime_type, status, promoted

1

There are 1 answers

2
Developerium On

you can do like this:

$posts=Post::model()->with(array(
    'comments'=>array(
        'scopes'=>array('recently','approved')
    ),
))->findAll();
// or since 1.1.7
$posts=Post::model()->findAll(array(
    'with'=>array(
        'comments'=>array(
            'scopes'=>array('recently','approved')
        ),
    ),
));

http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes