2015-10-15 01:30:34 2795次浏览 2条回答 0 悬赏 100 金钱

大家好,有表a、b、c。

a.id = b.aid,
b.id = c.bid
a->b,b->c 都是一对多的关系
并且 a的model中定义了 getB(hasmany),b的model中也定义了 getC(hasmany)

请问使用ar的情况下,如何才能尽可能少的进行sql查询。

$a = a::find()
    ->where([a::tableName() . '.id' => $ids])
    ->With(['b']) // 如果['b','c']会出错,因为a的model中没有定义c的关系。 b的model中有定义c的一对多关系
    ->all();

谢谢大家。

解决了。谢谢大家。可以这样

$a = a::find()
    ->where([a::tableName() . '.id' => $ids])
    ->With(['b','b.c']) 
    ->all();
  • 回答于 2015-10-18 22:49 举报

    这个有个类似yii1.1版本的relations的东西,我看到过,现在手机上不方便找,直接当做一个属性来访问的,比查看SQL语句要方便些,你的这种实现可能不是很好。类似如下代码。

    class Customer extends \yii\db\ActiveRecord
    {
        public function getOrders()
        {
            return $this->hasMany('Order', ['customer_id' => 'id']);
        }
    }
    
  • 回答于 2015-10-20 09:44 举报

    还是你的比较简单 我一般是这么写的

    $a = a::find()
        ->where([a::tableName() . '.id' => $ids])
        ->With(['b'=>function($query){$query->with('c');}]) 
        ->all();
    
您需要登录后才可以回答。登录 | 立即注册
xjdata
CEO

xjdata

注册时间:2011-12-07
最后登录:2024-05-05
在线时长:112小时38分
  • 粉丝23
  • 金钱14169
  • 威望75
  • 积分16039

热门问题