donglu7998 2015-01-07 19:11
浏览 34
已采纳

Yii和关系查询

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 );

  • 写回答

1条回答 默认 最新

  • duanbiao4025 2015-01-07 19:22
    关注

    When you do something like $model->Tech->TechSchedule[0]->Location->Customer, you will see that PHP will send a query to the database for each relation you try to access. In your case, that would probably amount to 4 different DB queries sent to the database. In many cases, you want to reduce the amount of times PHP queries the database because it is very costly (timewise).

    If you do something like User::model()->with('...'), all those relations will be brought together with the User model. This might save you time if you know you will access that related data (less roundtrips to the DB) but you may bring unnecessary data if you just want to access data in the User table.

    More information here(official docs)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。