簡體   English   中英

Yii cdbcriteria選擇關系的列

[英]Yii cdbcriteria select a relation's columns

我很難在Yii中給出的博客演示中選擇所有帖子的用戶名。

作者是帖子類與用戶的關系......

$criteria = new CDbCriteria;
$criteria->with='author';
$criteria->select='author.username';
$dataProvider=new CActiveDataProvider('Post', array(
    'criteria' => $criteria,
));
var_dump($dataProvider->getData());

錯誤:

活動記錄“發布”正在嘗試選擇無效的列“author.username”。 請注意,該列必須存在於表中,或者是具有別名的表達式。

什么with做的是eager loading ..that意味着關系的數據也將從數據庫加載非常久遠,而當日子會把你的時候調用的關系,不會有一個實際的查詢..

什么選擇是從數據庫中選擇它並將其映射到模型變量..

現在在你的情況下發生的事情是你正在嘗試在select中編寫一些關系列,即使沒有編寫它也會在select中存在, 但由於沒有相應的變量來映射這個值,所以yii會拋出一個錯誤。

首先,如果您需要auther的用戶名作為響應,您可以通過關系調用來獲取它,這不是數據庫調用,並且您不需要編寫選擇..

如果你想將用戶名作為post模型的一部分調用, 你必須將它聲明為模型中的屬性,然后在select中指定別名。

$criteria = new CDbCriteria;
$criteria->with='author';
$criteria->select='author.username as auther_username';
$dataProvider=new CActiveDataProvider('Post', array(
    'criteria' => $criteria,
));
var_dump($dataProvider->getData());

並在你的Post模型聲明..

public $auther_username;

現在它不會拋出錯誤,你可以通過兩種方式訪問​​用戶名.. $post->auther_username$post->auther->username

嘗試這個:

$criteria = new CDbCriteria;
$criteria->with=array('author'=>array('select'=>'username'));
$dataProvider=new CActiveDataProvider('Post', array(
    'criteria' => $criteria,
));
var_dump($dataProvider->getData());

來源: CActiveRecord.with

為了動態定制選項,我們應該將數組參數傳遞給with()方法。 數組鍵是關系名稱,數組值是相應的查詢選項。

嘗試這個:

$criteria = new CDbCriteria;
$criteria->with=array('author'=>array('select'=>'username'));

// you can still select Post table columns here
$criteria->select='post_content';

$dataProvider=new CActiveDataProvider('Post', array(
   'criteria' => $criteria,
));
var_dump($dataProvider->getData());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM