【控制器】HelloController.php
~~~
<?php
namespace app\controllers;
use yii\web\Controller;
use app\models\Test;
use app\models\Customer;
use app\models\Order;
class HelloController extends Controller {
public function actionIndex(){
// 根据顾客查询他/她的订单的信息
$customer = Customer::find()->where(['name'=>'zhangsan'])->one();
// $orders = $customer->hasMany(Order::className(), ['customer_id'=>'id'])->asArray()->all(); // 方法 1
// $orders = $customer->getOrders(); // 方法 2
$orders = $customer->orders; // 方法 3
print_r($orders);
echo '<hr/>';
// 根据订单查询顾客的信息
$order = Order::find()->where(['id'=>1])->one();
$customer = $order->customer;
print_r($customer);
}
}
~~~
【模型】Customer.php
~~~
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Customer extends ActiveRecord{
//帮助顾客获取订单信息
public function getOrders(){
$orders = $this->hasMany(Order::className(), ['customer_id'=>'id'])->asArray()->all();
return $orders;
}
}
~~~
【模型】Order.php
~~~
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Order extends ActiveRecord{
//根据订单后去订单信息
public function getCustomer(){
return $this->hasOne(Customer::className(), ['id'=>'customer_id'])->asArray();
}
}
~~~
源码下载:
链接:https://pan.baidu.com/s/11yhoLB_1Ef8FJryc9lYltw 密码:h0hj