Akash Pius
Akash Pius

Reputation: 336

how to join two table with relation in yii?

I have two tables company and users. In user table there is a field named company_id which relates users to the company. But not all users will be related to the company. There will be users without company id. Now I need to list the users in grid view using the relation. I related company to the users using the relation in yii.

public function relations() {
    return array('company' => array(self::BELONGS_TO, 'Company', 'company_id'));
}

But it showed error when I tried to display company name of each users. I think the issue is with the users which are not related to company. I searched for the answers, came up with the left join operation while giving relation.

public function relations() {
    return array('company' => array(self::BELONGS_TO, 'Company', 'company_id',
            'joinType' => 'LEFT JOIN',
            'on' => "(company.id=company_id)"));
}

But this too gives me error.

CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'company_id' in 'where clause'. The SQL statement executed was: SELECT company.id AS t1_c0, company.name AS t1_c1, company.telephone AS t1_c2, company.description AS t1_c3, company.address AS t1_c4, company.status AS t1_c5 FROM company company WHERE ((company.id=company_id)) AND (company.id=:ypl0)

Please help me in this issue. I am a beginner in yii.

Thanks in advance.

Upvotes: 1

Views: 742

Answers (1)

Vijay Joseph
Vijay Joseph

Reputation: 492

Please go through the below links to understand how Yii relations work:

http://www.yiiframework.com/wiki/181/relations-belongs_to-versus-has_one/

http://www.yiiframework.com/doc/guide/1.1/en/database.arr

Upvotes: 0

Related Questions