Sami Ghname
Sami Ghname

Reputation: 11

Yii Generate query with a relation condition (ActiveRecord)

I try to generate this query.

select * from jobs j inner join vacancies v on j.id = v.job_id where v.id = 2943 order by j.created_at desc limit 1

v.id just to test if the query work fine or not.

I have some condition from vacancies tables need to generate it with the jobs tables.

i try more than case to generate it.

this the relation from Vacancies model

'job' => array(self::BELONGS_TO, 'Jobs', 'job_id'),

this the relation from Jobs model

'vacancies' => array(self::HAS_MANY, 'Vacancies', 'job_id'),

and this my query.

$newJobs = Jobs::model()->findAll(

                    array('with'=>array(
                            'vacancies'=>array(
                                'condition'=>'vacancies.id = 2943',
                                'order'=>'t.created_at desc',
                            )
                        ),
                    'order'=>'t.created_at desc'
                    ,'limit'=>1
                    )
                );

but this give me the latest jobs without the any condition from vacancies as id.

and try this with some scopes in the Jobs model.

$newJobs = Jobs::model()->isOffline()->isApproved()->recent()->findAll(array(
                            'with'=>array(
                                'vacancies'=>array(
                                    'condition'=>'vacancies.id=2268'
                                )
                            )
                        )
                        );

the scopes

    public function recent($limit=1)
    {
        $this->getDbCriteria()->mergeWith(array(
            'order'=>'t.created_at DESC',
            'limit'=>$limit,
        ));
        return $this;
    }

    public function isOffline($offline = 'False')
    {
        $this->getDbCriteria()->mergeWith(array(
            'condition'=>"t.offline = '$offline' OR t.offline is null",
        ));
        return $this;
    }

    public function isApproved($approved = 'False')
    {
        $this->getDbCriteria()->mergeWith(array(
            'condition'=>"t.approved= '$approved'",
        ));
        return $this;
    }

And not work is still give me the latest jobs without the condition from vacancies.

Can any one help me.

Upvotes: 0

Views: 8440

Answers (1)

urmaul
urmaul

Reputation: 7340

Try this:

                    ...
                    array('with'=>array(
                        'vacancies'=>array(
                            'alias'=>'v',
                            'joinType'=>'INNER JOIN',
                            'condition'=>'v.id = 2943',
                            'order'=>'t.created_at desc',
                        )
                    ),
                    ...

http://www.yiiframework.com/doc/guide/1.1/en/database.arr#performing-relational-query-without-getting-related-models

Upvotes: 1

Related Questions