yii的relations要怎麼寫?熟悉YII的朋友們幫看看

來源:互聯網
上載者:User
表一 (city)
id name code
1 北京 0001
2 上海 0002


表二 (user)
id username citycode
1 小李 0001
2 小王 0001
3 小紅 0002

第二個表的citycode欄位是第一個表的code欄位相對應

在YII的model裡要怎麼寫這兩個model的relations要怎麼寫呢?
city表的對應model (City.php)
 array(self::HAS_MANY, 'User', 'code'),這裡不知道要怎麼寫,這樣寫不知道對不對?);}//…………}


user表的對應model (User.php)
 array(self::BELONGS_TO, 'City', 'citycode'),這裡不知道要怎麼寫,這樣寫不知道對不對?);}//…………}



按我上面的寫法,在視圖(view)檔案裡 使用如:$data->city->name 或 $data->user->username會出錯。
初學YII 對relation不知道要怎麼寫,麻煩知道的朋友指導下,謝謝了!


回複討論(解決方案)

沒人幫解決嗎?

我也是個新手,說說我的看法!
首先你的表就有問題,作為兩個表產生 關聯是因為有 外鍵約束。而你的第一個表中的欄位 citycode不是主鍵,那麼就不能作為外鍵。就談不上,兩個表之間的聯絡了。


如果,你的表建立如下:
create table city(
cityCode varchar(25) not null primary key,
name varchar(128) not null,
);

create table user(
id int(11) primary key,
name varchar(128) not null,
cityCode varchar(25) not null,
foreign key(cityCode) references city(cityCode),
);

建立了外鍵之後,
描述 關聯關係:
User 中:
return array('user'=>array(self::BELONGS_TO, 'City', 'cityCode'));

City中:
return array('city'=>array(self::HAS_MANY, 'User', 'cityCode'));

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.