Darshan
Darshan

Reputation: 760

Symfony Propel model layer

I have three tables such as user, job and job_applied. user table has uid , job table has jid and job_applied has uid and jid . I need to get job title, description, position of job table according to uid and jid of job_applied table. I'm able to get values from below code, But i think this is the wrong way (crude way) .

$this->jobapplieds = $this->getUser()->getUser()->getJobApplieds();

foreach($jobapplieds as $ja)   
{    
    $c = new Criteria();

    $c->clearSelectColumns();

    $c->addSelectColumn(JobPeer::TITLE);

    $c->addSelectColumn(JobPeer::DESCRIPTION);

    $c->addSelectColumn(JobPeer::STATUS);

    $c->add(JobPeer::JID,$ja->getJid());

    $rs = JobPeer::doSelectRS($c); 

    while($rs->next())
    {
        echo $rs->getString(1); 
        print $rs->getString(2);
    }

    echo $ja->getAppliedAt();

}

Upvotes: 1

Views: 335

Answers (1)

Jan Fabry
Jan Fabry

Reputation: 7361

If the current user has applied for 10 jobs, you currently do 10 + 1 queries (one to get all applications and then one per job). You can improve this in two ways:

Instead of doing 10 queries in your loop, you can first collect all jid values in an array and then do an IN query, so you do 1 + 1 queries.

$this->jobapplieds = $this->getUser()->getUser()->getJobApplieds();
$jobapplieds_by_jid = array();
foreach ($jobapplieds as $ja)
{
    // If you can apply multiple times for the same job, this should be a second-level array
    $jobapplieds_by_jid[$ja->getJid()] = $ja;
}

$c = new Criteria();
$c->add(JobPeer::JID, array_keys($jobapplieds_by_jid), Criteria::IN);
$jobs = JobPeer::doSelect($c); 

foreach ($jobs as $job)
{
    echo $job->getTitle();
    echo $job->getDescription();
    echo $jobapplieds_by_jid[$job->getJid()]->getAppliedAt();
}

The other option is to do one query where you start with the job table, join it with the job_applied table, and set the uid of the job_applied table to your current user ID. This should execute only one query.

$c = new Criteria();
$c->add(JobAppliedPeer::UID, $this->getUser()->getUser()->getUid());
$jobs = JobPeer::doSelectJoinJobApplied($c);
foreach ($jobs as $job)
{
    echo $job->getTitle();
    echo $job->getDescription();
    echo $job->getJobApplied()->getAppliedAt();
}

Upvotes: 1

Related Questions