码迷,mamicode.com
首页 > 其他好文 > 详细

Yii2中多表关联查询(with、join、joinwith)

时间:2015-08-12 23:34:56      阅读:831      评论:0      收藏:0      [点我收藏+]

标签:

表结构

现在有客户表、订单表、图书表、作者表,

  • 客户表Customer   (id  customer_name)
  • 订单表Order         (id  order_name   customer_id   book_id)
  • 图书表Book          (id  book_name    author_id)
  • 作者表Author        (id  author_name)

模型定义

下面是这4个个模型的定义,只写出其中的关联

Customer 

class Customer extends \yii\db\ActiveRecord
{
  public function getOrders()
  {
    return $this->hasMany(Order::className(), [‘customer_id‘ => ‘id‘]);
  }
}

Order 

class Order extends \yii\db\ActiveRecord
{
  public function getCustomer()
  {
    return $this->hasOne(Customer::className(), [‘id‘ => ‘customer_id‘]);
  }

  public function getBooks()
  {
    return $this->hasMany(Book::className(), [‘id‘ => ‘book_id‘]);
  }
}

Book 

class Book extends \yii\db\ActiveRecord
{
  public function getAuthor()
  {
    return $this->hasOne(Author::className(), [‘id‘ => ‘author_id‘]);
  }
}

关联的使用

现在我们获取一个客户的所有的订单信息

$customer = Customer::findOne(1); // 获取一个客户信息
$orders = $customer->orders; // 通过在Customer中定义的关联方法(getOrders())来获取这个客户的所有的订单。

上面的两行代码会生成如下sql语句

SELECT * FROM customer WHERE id=1;
SELECT * FROM order WHERE customer_id=1;

关联结果缓存

如果客户的订单改变了,我们再重新调用$orders = $customer->orders;

再次得到订单的时候你会发现没有变化。原因是只会在第一次执行$customer->orders的时候才会去数据库里面查询,然后会把结果缓存起来,以后查询的时候都不会再执行sql。那么如果我想再次执行sql如何做呢?可以执行:

 

unset($customer->orders);
$customer->orders;

定义多个关联

同样,我们还可以在Customer里面定义多个关联。
如返回总数大于100的订单。

 

class Customer extends \yii\db\ActiveRecord
{
  public function getBigOrders($threshold = 100)
  {
    return $this->hasMany(Order::className(), [‘customer_id‘ => ‘id‘])
          ->where(‘subtotal > :threshold‘, [‘:threshold‘ => $threshold])
          ->orderBy(‘id‘);
  }
}

关联的两种访问方式

$customer->bigOrders // 属性方式访问

将会得到大于100的所有的订单。如果要返回大于200的订单可以这样写:

$orders = $customer->getBigOrders(200)->all(); // 对象方式访问

从上面可以看出访问一个关联的时候有两种方法

  • 如果以函数的方式调用,会返回一个 ActiveQuery 对象($customer->getOrders()->all())
  • 如果以属性的方式调用,会直接返回模型的结果($customer->orders)

with的使用

如果现在我们要取出100个用户,然后访问每个用户的订单,使用with写出如下代码:

 

// 先执行sql: SELECT * FROM customer LIMIT 100;
$customers = Customer::find()->limit(100)
                ->with(‘orders‘)->all();

 

foreach ($customers as $customer) {
  $orders = $customer->orders;
}

如果使用了select来指定返回的列,一定要确保返回的列里面包含所关联的模型的关联字段,否则将不会返回关联的表的Model:

$orders = Order::find()->select([‘id‘, ‘amount‘])->with(‘customer‘)->all();
// $orders[0]->customer 的结果将会是null
// 因为上面的select中没有返回所关联的模型(customer)中的指定的关联字段。

// 如果加上customer_id,$orders[0]->customer就可以返回正确的结果
$orders = Order::find()->select([‘id‘, ‘amount‘, ‘customer_id‘])->with(‘customer‘)->all();

给with加过滤条件

查询一个客户大于100的订单

 

//首先执行sql: SELECT * FROM customer WHERE id=1
$customer = Customer::findOne(1);

 

// 再执行查询订单的sql语句:SELECT * FROM order WHERE customer_id=1 AND subtotal>100
$orders = $customer->getOrders()->where(‘subtotal>100‘)->all();

查询100个客户的,每个客户的总合大于100的订单:

// 下面的代码会执行sql语句:
// SELECT * FROM customer LIMIT 100
// SELECT * FROM order WHERE customer_id IN (1,2,...) AND subtotal>100
$customers = Customer::find()->limit(100)->with([
‘orders‘ => function($query) {
$query->andWhere(‘subtotal>100‘);
},
])->all();

使用joinWith进行表关联

我们都知道可以用join on来写多个表之间的关联。先看看yii2中joinWith的声明
joinWith( $with, $eagerLoading = true, $joinType = ‘LEFT JOIN‘ )

  • $with 数据类型为字符串或数组,
    如果为字符串,则为模型中定义的关联的名称(可以为子关联)。
    如果为数组,键为model中以getXXX格式定义的关联,值为对这个关联的进一步的回调操作。
  • $eagerLoading 是否加载在$with中关联的模型的数据。
  • $joinType 联接类型,可用值为:LEFT JOIN、INNER JOIN,默认值为LEFT JOIN

 

 

 

 

// 订单表和客户表以Left join的方式关联。
// 查找所有订单,并以客户 ID 和订单 ID 排序
$orders = Order::find()->joinWith(‘customer‘)->orderBy(‘customer.id, order.id‘)->all();

// 订单表和客户表以Inner join的方式关联
// 查找所有的订单和书
$orders = Order::find()->innerJoinWith(‘books‘)->all();

// 使用inner join 连接order中的 books关联和customer关联。
// 并对custmer关联再次进行回调过滤:找出24小时内注册客户包含书籍的订单
$orders = Order::find()->innerJoinWith([
‘books‘,
‘customer‘ => function ($query) {
$query->where(‘customer.created_at > ‘ . (time() - 24 * 3600));
}
])->all();

// 使用left join连接 books关联,books关联再用left join 连接 author关联
$orders = Order::find()->joinWith(‘books.author‘)->all();

在实现上,Yii 先执行满足JOIN查询条件的SQL语句,把结果填充到主模型中, 然后再为每个关联执行一条查询语句, 并填充相应的关联模型。

// Order和books关联 inner join ,但不获取books关联对应的数据
$orders = Order::find()->innerJoinWith(‘books‘, false)->all();

On条件

在定义关联的时候还可以指定on条件

 

class User extends ActiveRecord
{
  public function getBooks()
  {
    return $this->hasMany(Item::className(), [‘owner_id‘ => ‘id‘])->onCondition([‘category_id‘ => 1]);
  }
}

 

Yii2中多表关联查询(with、join、joinwith)

标签:

原文地址:http://www.cnblogs.com/itsharehome/p/4725776.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!