2011-06-19 32 views
1

我覺得數據庫操作在指南上沒有很好地解釋。我無法理解它。因爲這個,我有一個問題。我問它Yii論壇,但沒有任何答案。例如,這是我的社交表。從Yii Framework的數據庫中讀取乘以行

+------------+---------------------------+--------------+--------------+---------------+ 
| socials_ID | socials_link    | socials_type | socials_user | socials_order | 
+------------+---------------------------+--------------+--------------+---------------+ 
|   48 | link      |   8 |   1 |    4 | 
|   47 | blablabla     |   11 |   1 |    3 | 
|  301 | userlinkuse    |   9 |   1 |    6 | 
+------------+---------------------------+--------------+--------------+---------------+ 

我想從此表中獲取socials_user collumn等於1的所有數據。可以有幾行(在這個例子中有3行)。

我應該使用什麼方法?我試試這個:

   $allSocial = ''; 
       $socials=Socials::model()->findByAttributes(array('socials_user'=>1)); 
       foreach ($socials as $social) 
       { 
         $type = $social["socials_type"]; 
         $allSocial .= $type . ","; 
       } 
       return $allSocial; 

但這是返回4,1,8,1,4。 (第一行的每個柱子的第一個字母/數字)

我該如何使用它? findByAttributes AR將LIMIT 1;添加到SQL?

+0

* [A模型代表一個單獨的數據對象(http://www.yiiframework.com/doc/guide/1.1/en /basics.model)* – hakre

+0

@hakre,那麼我怎樣才能列出socials_user collumn等於1的數據呢? – Eray

回答

5

使用這種方法來獲得來自其表socials_user列值相等的記錄爲1

$socials=Socials::model()->findAll('socials_user=:socials_user', array(':socials_user'=>1)); 
3

您正在使用來自YII的模型。模型始終代表YII中的一個對象。這就是爲什麼它看起來像你描述的那樣有一個LIMIT 1

您需要查詢數據庫來返回一組行。下面是一些誼數據庫訪問代碼示例給一個畫面是如何工作的(from here):

$dataReader=$command->query(); 
// calling read() repeatedly until it returns false 
while(($row=$dataReader->read())!==false) { ... } 
// using foreach to traverse through every row of data 
foreach($dataReader as $row) { ... } 
// retrieving all rows at once in a single array 
$rows=$dataReader->readAll(); 

我不知道,如果你已經有了一個數據庫連接設置,但我以爲這樣你已經使用一個數據庫。因此,這是你所需要的訪問DB Command對象,然後實際調用query()from here):如果使用的

$connection=Yii::app()->db; // assuming you have configured a "db" connection 
// If not, you may explicitly create a connection: 
// $connection=new CDbConnection($dsn,$username,$password); 
$command=$connection->createCommand($sql); 
// if needed, the SQL statement may be updated as follows: 
// $command->text=$newSQL; 

希望這信息給你。

+0

謝謝你hakre,你能適應這個我的例子嗎?所以,我可以很好地理解它。 – Eray

+0

請檢查Varun Mittal的答案。我認爲這更容易處理。 – hakre