Yii 2:执行useles查询

rea*_*ebo 3 yii2

我有一个数据表,其product_id指向product.id

在ProductQuery中,扩展了ActiveQuery,我创建了这些函数

public function all($db = null)
{
    return parent::all($db);
}

public function not_g00()
{
    $this->andWhere('category_code <> "G00"');
    return $this;
}


public function without_datasheet()
{
    $this->joinWith('datasheet');
    $this->andWhere(['{{%datasheet}}.id'=> null]);
    return $this;
}

public function from_newest()
{
    $this->addOrderBy(['created_on' => SORT_DESC]);
    return $this;
}
Run Code Online (Sandbox Code Playgroud)

虽然find实际上被重写为Product类

public static function find()
{
    return new \frontend\models\query\ProductQuery(get_called_class());
}
Run Code Online (Sandbox Code Playgroud)

我用作:

$products_without_datasheet = Product::find()
        ->not_g00()
        ->without_datasheet()
        ->from_newest()
        ->all();
Run Code Online (Sandbox Code Playgroud)

结果是第一个查询,简单完美:

SELECT `tbl_product`.* FROM `tbl_product` LEFT JOIN `tbl_datasheet` 
ON `tbl_product`.`id` = `tbl_datasheet`.`product_id`
WHERE (category_code <> "G00") AND (`tbl_datasheet`.id IS NULL) 
ORDER BY `created_on` DESC
Run Code Online (Sandbox Code Playgroud)

但调试日志显示在此之后执行SECOND查询.

SELECT * FROM `tbl_datasheet` WHERE `product_id` IN (7541, 7929,... )
Run Code Online (Sandbox Code Playgroud)

调试告诉我这个查询被调用datasheet::find()->all()... but why?!,由all()调用

$products_without_datasheet = Product::find()
        ->not_g00()
        ->without_datasheet()
        ->from_newest()
        ->all(); 
Run Code Online (Sandbox Code Playgroud)

为什么?我究竟做错了什么?当第一个查询已经完美时,为什么它会执行2个查询?

soj*_*oju 5

您正在使用$this->joinWith('datasheet');,如果您不想获取相关数据表,则应该使用$this->joinWith('datasheet', false);

关于joinWith():

如果$ eagerLoading参数为true,则该方法也会急切加载指定的关系,这相当于使用指定的关系调用with().

了解更多joinWith().