1

YiiのARモデルの関係は配列として返されると思います。しかし、「YiiとPHPを使用したWebアプリケーション開発」という本では、テーマをオブジェクトインスタンスとして使用しようとすると、エラーが発生します。私は何かを見逃しているのですか、それとも間違った理解をしているのですか、それとも本の間違いですか?

たとえば、「コメント」ARモデルクラスには次のものがあります。

public function relations()
{

    return array(
        'author' => array(self::BELONGS_TO, 'User', 'create_user_id'),
    );
}

本は「ユーザー名」を次のように参照します:

$comment->author->username

そして私は使用します:

$comment->author['username']

どちらが正しいですか?

更新->関連するすべてのコードをここに配置します: ARモデル:

/**
 * This is the model class for table "tbl_comment".
 *
 * The followings are the available columns in table 'tbl_comment':
 * @property integer $id
 * @property string $content
 * @property integer $issue_id
 * @property string $create_time
 * @property integer $create_user_id
 * @property string $update_time
 * @property integer $update_user_id
 *
 * The followings are the available model relations:
 * @property User $updateUser
 * @property Issue $issue
 * @property User $createUser
 */
class Comment extends TrackStarActiveRecord
{
/**book
 */
public function recent($limit=5)
{
    $this->getDbCriteria()->mergeWith(array(
    'order'=>'t.create_time DESC',
    'limit'=>$limit,)
    );
    return $this;   
}
/**
 * Returns the static model of the specified AR class.
 * @param string $className active record class name.
 * @return Comment the static model class
 */
public static function model($className=__CLASS__)
{
    return parent::model($className);
}

/**
 * @return string the associated database table name
 */
public function tableName()
{
    return 'tbl_comment';
}

/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('content, issue_id', 'required'),
        array('issue_id, create_user_id, update_user_id', 'numerical', 'integerOnly'=>true),
        array('create_time, update_time', 'safe'),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('id, content, issue_id, create_time, create_user_id, update_time, update_user_id', 'safe', 'on'=>'search'),
    );
}

/**
 * @return array relational rules.
 */
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'updateUser' => array(self::BELONGS_TO, 'User', 'update_user_id'),
        'issue' => array(self::BELONGS_TO, 'Issue', 'issue_id'),
        'author' => array(self::BELONGS_TO, 'User', 'create_user_id'),
    );
}

/**
 * @return array customized attribute labels (name=>label)
 */
public function attributeLabels()
{
    return array(
        'id' => 'ID',
        'content' => 'Content',
        'issue_id' => 'Issue',
        'create_time' => 'Create Time',
        'create_user_id' => 'Create User',
        'update_time' => 'Update Time',
        'update_user_id' => 'Update User',
    );
}

/**
 * Retrieves a list of models based on the current search/filter conditions.
 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
 */
public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id);
    $criteria->compare('content',$this->content,true);
    $criteria->compare('issue_id',$this->issue_id);
    $criteria->compare('create_time',$this->create_time,true);
    $criteria->compare('create_user_id',$this->create_user_id);
    $criteria->compare('update_time',$this->update_time,true);
    $criteria->compare('update_user_id',$this->update_user_id);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
  }
  }

ウィジェットコンポーネント:

<?php
/**
* RecentCommentsWidget is a Yii widget used to display a list of
recent comments
*/
class RecentCommentsWidget extends CWidget
{
private $_comments;
public $displayLimit = 5;
public $projectId = null;
public function init()
{
    if(null !== $this->projectId)
        $this->_comments = Comment::model()-          >with(array('issue'=>array('condition'=>'project_id='.$this->projectId)))->recent($this->displayLimit)->findAll();
    else
        $this->_comments = Comment::model()->recent($this->displayLimit)->findAll();
}
public function getData()
{
return $this->_comments;
}
public function run()
{
// this method is called by CController::endWidget()
$this->render('recentCommentsWidget');
}
}

ウィジェットビュー:

<ul>
    <?php foreach($this->getData() as $comment): ?>
<div class="author">
    <?php echo $comment->author->username; ?> added a comment.
</div>
<div class="issue">
    <?php echo CHtml::link(CHtml::encode($comment->issue->name),
    array('issue/view', 'id'=>$comment->issue->id)); ?>
</div>
    <?php endforeach; ?>
</ul>

このコードは非オブジェクトエラーになりますが、変更すると

$comment->author->username

$ comment->author['username']に正常に動作します。オブジェクトアクセスメソッドによる$issueでどのように機能するのだろうか。

4

2 に答える 2

0

これらのアクセス方法はどちらも機能します。CActiveRecordインスタンスは PHPArrayAccessクラスを使用して、その属性への配列スタイルのアクセスを提供します。

ただし、関係タイプを参照している可能性があります。

HAS_ONE&BELONGS_TOどちらも、例として示したように直接使用できる単一のオブジェクトを返します。NULLこれらは、行が見つからない場合にも返されます。

HAS_MANY&MANY_MANYリレーションは配列を返します。これは、$model->authors[0]->nameまたはのように使用します$model->authors[1]->nameArray行が見つからない場合、これらは返されて空になります。

STATリレーションは少し異なり、単一のスカラー値 (整数、文字列、ブール値など) を返します。戻り値0が見つかりませんが、これは次の方法で構成できますdefaultValue

詳細については、ここを参照してください。

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

于 2013-02-15T13:58:04.540 に答える
0

推奨されるフォームは次のとおりです。

$comment->author->username

以下のコードを使用できます...

$comment->author['username']

...PHP はオブジェクトを配列として扱うためです。

于 2013-02-15T14:08:31.307 に答える