需在customer模型中定义getbigorders方法并用innerjoinwith构建activedataprovider,否则触发activequery类型错误;控制器中必须将innerjoinwith('bigorders')置于query参数内,视图中用gridview自动渲染。

要在Yii2中准确查出关联订单金额超100元的客户列表,并在GridView中分页展示,不能直接用数组或原生SQL命令创建数据提供器,否则会触发ActiveDataProvider不兼容错误。
定义关联查询方法
在Customer模型中添加getBigOrders方法,明确指定关联条件和筛选阈值。
打开models/Customer.php,在类内部添加以下方法:
public function getBigOrders($threshold = 100) { return $this->hasMany(Order::className(), ['customer_id' => 'id']) ->where('subtotal > :threshold', [':threshold' => $threshold]) ->orderBy('id'); }
这一步必须写在Customer类里,否则控制器调用innerJoinWith('bigorders')时会找不到关系定义。注意方法名getBigOrders对应调用时的小写形式bigorders,大小写敏感。
控制器中构建数据提供器
进入controllers/SiteController.php,新增actionGetorders方法。
使用innerJoinWith而非with,确保生成的SQL是INNER JOIN而不是两次独立查询。
【innerJoinWith('bigorders')必须放在query参数内,不能写成query→innerJoinWith()】
完整代码段:
$dataProvider = new ActiveDataProvider([ 'query' => Customer::find()->innerJoinWith('bigorders'), 'pagination' => ['pageSize' => 10], ])
如果误用all()或createCommand(),ActiveDataProvider会立刻抛出“must be instance of ActiveQuery”异常——这是最常踩的坑。
视图中渲染GridView
在views/site/index.php中引入GridView组件并绑定数据源。
第一行写:use yii\grid\GridView;
紧接着写:= GridView::widget(['dataProvider' => $dataProvider]); ?>
这行代码会自动读取Customer模型的attributeLabels作为表头,无需额外配置columns。
若Customer模型未定义attributeLabels()方法,表头将显示原始字段名如id、name,不影响数据渲染。











