Yii中的relations方法

2021-06-12 13:13:17 字數 1609 閱讀 2047

以blog示例: 重點看注釋

user類中的relations方法如下 

public function relations()

post中的方法如下 : 

public function relations()

comment中的ralations方法如下:

public function attributelabels()    //名字和現實標籤的對映陣列

在控制器中寫個方法測試一下結果:

public function actionrq()

echo $post->author->username."

"; }

echo "";

$user = user::model()->with('posts.comments')->findbypk(1);

//$user = user::model()->findbypk(1); 這一句和上一句是一樣的,因為在user的relations宣告的posts也已經加上了關聯查詢:with=>'comments'

foreach($user->posts as $post)

echo ")".$post->tags."

"; }

echo "";

$criteria = new cdbcriteria;

//$criteria->select = "username";

//$criteria->order

//$criteria->limit

//$criteria->condition

//$criteria->params

$criteria->with = array(

'posts.comments',

);$users = user::model()->findall($criteria);

foreach($users as $user)

echo ")".$post->tags."

"; }

} //動態關聯查詢,也就是在查詢的時候覆蓋relations中設定的關聯的選項

echo "";

$user=user::model()->with(array(

'posts'=>array(

'order'=>'posts.update_time desc',

'with'=>array('comments'=>array('order'=>'comments.id asc')),

//'together'=>false, //關聯宣告中設定together 選項為false 以便一些表被連線在單獨的sql語句中,分為幾個sql語句執行

),))->findbypk(1);

echo "demo 的posts數量為:".$user->postcount;

echo "

"; foreach($user->posts as $post)

echo ")";

echo "

"; }

}

Yii中relations的用法

class amspricenewcar extends amcpricenewcar public function searchmaintain 1 這裡遇到的問題,用了 criteria join方法,查詢報錯,原因是gocar mileage表與主表中有欄位名相同,於是用了 criteria...

yii的relations方法的使用

在組織資料庫時,需要使用主鍵與外來鍵約束才能使用activereocrd的關係操作 兩張表之間的關係無非三種 一對多 一對一 多對多 在ar中,定義了四種關係 關係定義 例子belongs to a和b的關係是一對多,那麼b屬於a post屬於user has many a和b之間的關係是一對多,那...

Yii的relations方法的使用

兩張表之間的關係無非三種 一對多 一對一 多對多 在ar中,定義了四種關係 關係定義 例子belongs to a和b的關係是一對多,那麼b屬於a post屬於user has many a和b之間的關係是一對多,那麼a有多個b user有多個post has one 這是has many的一種特殊...