如何在yii2中实现多个左连接?

时间:2014-07-03 10:49:19

标签: php yii2

我有3个名为stock,product,users的表。我有一个加入查询,如下所示。有人可以告诉我如何在yii2中实现它吗?

SELECT 
    stock.sale_price_per_unit,
    sum(stock.quantity),
    product.product_name,
    users.username

FROM
    stock
LEFT JOIN product ON product.product_id=stock.product_id
LEFT JOIN users ON users.user_id=stock.seller_id
WHERE stock.product_id=3
GROUP BY stock.seller_id

3 个答案:

答案 0 :(得分:5)

参考http://www.yiiframework.com/doc-2.0/guide-active-record.html#joining-with-relationshttp://www.yiiframework.com/forum/index.php/topic/50423-joins-are-back/

$orders = Order::find()->joinWith('customer')->orderBy('customer.id, order.id')->all();

因此您的代码应如下所示:

$query = Stock::find()
->joinWith(['product', 'users']);

$items = $query
    ->select([
        'sale_price_per_unit',
        'sum(quantity)',
        'product.product_name',
        'users.username'])
    ->where(['stock.product_id'=>3])
    ->groupBy('seller_id')
    ->all();

在Stock模型中声明的关系“product”和“users”: HAS_MANY:

public function getUsers()
{
  return $this->hasMany(User::className(), ['seller_id' => 'user_id']);
}

HAS_ONE

public function getProduct()
{
  return $this->hasOne(Product::className(), ['product_id' => 'product_id']);
}

答案 1 :(得分:0)

以下是完整的代码连接在模型 Geography.php 这里我有模型地理,我在yii2的地理表中绑定了三个表

#####**Create Relation With Country Table** 

public function getCountry() {
    return $this->hasOne(Country::className(), ['id' => 'country_id']);
}

#####**Create Relation With State Table** 

public function getState() {
    return $this->hasOne(State::className(), ['id' => 'state_id']);
}

**#####Create Relation With City Table** 

public function getCity() {
    return $this->hasOne(City::className(), ['id' => 'city_id']);
}

答案 2 :(得分:-1)

    $criteria = new CDbCriteria;
$criteria->select = 'DISTINCT t.*';
                                        $criteria->join = ' LEFT JOIN `shared_items` AS `si` ON t.workspace_id = si.workspace_id';
                                        $criteria->addCondition('t.status_id != ' . ProjectStatuses::STATUS_CLOSED);
                                        $criteria->addCondition('t.workspace_id = ' . $workspace_id);