0

I have some tables that have foreign key references:

User -> Tech -> TechSchedule -> Location -> Customer

It seems that I can use the following query once to get any related data to the user. Consider the following query:

// load the user model
$model = User::model()->findByPk( Yii::app()->user->id );

// print
echo "<pre>", print_r( $model->attributes ), "</pre>";

// print more about the user
echo "<pre>", print_r( $model->Tech->TechSchedule[0]->Location->Customer ), "</pre>";

Prints out

Array
(
    [user_id] => 1
    [username] => someusername
    [password] => somepassword
    [salt] => somesalt
)

Customer Object
(
    [_new:CActiveRecord:private] => 
    [_attributes:CActiveRecord:private] => Array
        (
            [customer_id] => 14
            [more customer data...]
    )

[_related:CActiveRecord:private] => Array
    (
    )

[_c:CActiveRecord:private] => 
[_pk:CActiveRecord:private] => 14
[_alias:CActiveRecord:private] => t
[_errors:CModel:private] => Array
    (
    )

[_validators:CModel:private] => 
[_scenario:CModel:private] => update
[_e:CComponent:private] => 
[_m:CComponent:private] => 
)`

Is this normal behavior? If so, what would the purpose be of going through the hassle of writing relational queries, such as

$model = User::model()->with('Tech.TechSchedule.Location.Customer')->findByPk( Yii::app()->user->id );

4

1 に答える 1

1

のようなことをすると、アクセスしようとするリレーションごと$model->Tech->TechSchedule[0]->Location->Customerに、PHP がデータベースにクエリを送信することがわかります。あなたの場合、それはおそらくデータベースに送信される4つの異なるDBクエリになります。多くの場合、(時間的に) 非常にコストがかかるため、PHP がデータベースに照会する回数を減らしたいと考えます。

のようなことをするとUser::model()->with('...')、これらすべてのリレーションが User モデルにまとめられます。関連するデータにアクセスすることがわかっている場合 (DB へのラウンドトリップが少ない) は、時間を節約できますが、User テーブルのデータにアクセスしたいだけの場合は、不要なデータを持ち込む可能性があります。

詳細はこちら(公式ドキュメント)

于 2015-01-07T19:22:20.747 に答える