来源:我的博客站 OceanicKang |《YII2.0 关联表查询》
##Model层
/**
* 关联 207状态 进货订单
*/
public function getOrder()
{
return $this
-> hasMany(Order::className(), ['is_purchase' => 'supplier_id'])
-> andWhere(['order_status' => ['207']]);
}
##Controller层
$model = Account::find()
-> where('yl_account.account_id = :account_id', [':account_id' => $account_id])
// -> joinWith(['order']
-> with([
'order' => function($query) use ($start_date, $end_date) {
// 额外添加其他条件
$query -> andWhere('updated >= :start_date and updated < :end_date', [':start_date' => $start_date, 'end_date' => $end_date]);
}
])
-> asArray() -> one();
###joinWith 和 with 的区别
- 当你使用关联查询的时候, 你想排除掉副表不满足的条件下, 主表也给排除掉, 那么我们这时候就选 JoinWith
- 当你不介意对应的副表是否满足条件时, 只需要把主表显示出来就行了, 那么我们这时就选with
- 观察sql,你会发现, 用with的时候, 没有with对应的sql语句, 而JoinWith对应的sql语句是存在的
- 这些区别当然不是我总结的,链接地址在这http://www.yiichina.com/tutorial/1081,哈哈