yii2多表联查
1、表结构分别有:
order表:
create table 'order'(
'order_id' int(11) not null auto_increment,
'order_info_id' int(11) not null,
'name' varchar(50) not null,
'number' varchar(50) not null,
primary key ('order_id')
);
order_info表:
create table 'order_info'(
'order_info_id' int(11) not null auto_increment,
'name' varchar(50) not null,
'number' varchar(50) not null,
'create_time' int(11) not null,
primary key ('order_info_id')
)
2、Model层:
OrderModel代码:
namespace app\models;
use yii\db\ActiveRecord;
class OrderModel extent ActiveRecord{
//关联orderInfo表
//hasOne表示一对一
//hasMany表示一对多
public function getOrderInfo(){
return $this->hasOne(orderInfo::className(),['order_info_id'=>'order_info_id']);
}
//连表查询
//asArray()表示将对象转换数据
//alias相当于as
//joinWith($with,$eagerLoading = true ,$joinType = 'left join')
// $with数据类型为字符串或数组
// 如果为字符串,则为模型中定义的关联的名称(可以为子关联)
// 如果为数组,键为model中的getXXX格式定义的关联,值为对这个关联的进一步的回调操作
// $eagerLoading是否加载在$with中关联的模型的数据 默认为true(表示加载)
// $joinType联接类型 可为:left join 、inner join ,默认值为left join
public function selectOrderAndOrderInfo(){
return OrderModel::find()->alias('a')->joinWith('orderInfo as b')->asArray()->all();
}
}
3、Controller层调用:
$model = new Order;
$res = $model->selectOrderAndOrderInfo();

浙公网安备 33010602011771号