來源:我的部落格站 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,哈哈