1、首先准备两张表:
customer(用户表)(id, name)
order(订单表)(id, customer_id, price)
customer 表和 order 表之间是一对多的关系,通过 customer_id 字段关联。
2、建立相应的模型文件 customer.php 和 order.php 文件。
customer.php文件添加getorder()方法:
<?php namespace app\models; u yii; /** * this is tat是哪个国家he model class for t怜悯的反义词able "customer". * * @property int $id * @property string $name 用户姓名 */class customer extends \yii\db\activerecord{ /** * 获取订单信息 */ public function getorder() { // 一个用户对应多个订单,一对多的关系使用hasmany()关联 return $this->hasmany(order::classname(), ['customer_id' => 'id'])->asarray(); } }
order.php文件添加getcustomer()方法:
<?php namespace app\models; u yii; /** * this is the model class for table "order". * * @property int $id * @property int $customer_id 用户id * @property string $price 价格 */class order extends \yii\db\activerecord{ /** * 获取用户信息 */ public function getcustomer() { // 一个订单对应一个用户,一对一的关系使用hasone()关联 return $this->hasone(customer::classname(), ['id' => 'customer_id'])->asarray(); }}
// 查询客户名为张三的订单信息$customer = customer::find()->where(['nam英语4级多少分算过e' => '张三'])->one();// 可以通过$customer->getorder()方法调用customer.php模型中getorder()方法$orders = $customer->getorder()->all();// 也可以使用$customer->order属性调用,// 当程序没有找到order属性时,php会调用__get()函数,程序会自动寻找getorder()方法调用// 这里不用加all(),程序会自动识别,如果使用的是hasmany则加all(),hasone则加上one()$orders = $customer->order;var_dump($orders);exit; // 查询订单id为1的客户信息$order = order::find()->where(['id' => 1])->one();// 调用order.php模型中getcustomer()方法$customer = $order->customer;var_dump($customer);exit;
使用上面的关联查询时有个问题就是数据量大的时候性能问题。
$customers = customer::find()->all(); // 相当于执行 lect * from customerforeach ($customers as $customer) { $orders = $customer->order; // 相当于执行 lect * from order where customer_id = id;}
假如$customers中有100条数据,则要循环查询100次,整个程序需要执行sql语句101次。
这时可以使用with():
// 相当于执行了两条sql语句 lect * from customer// lect * from order where customer_id in(...)$customers = customer::find()->with('order')->asarray()->all();foreach ($customers as $customer) { $orders = $customer['order']; // 取得order表的关联数据}
joinwith()的用法和with()差不多,joinwith()可以指定连接类型,默认left join连接。
1、在模型中定义hasmany,hasone方法时,最好不要加上all(),one()。调用$customer->order时程序会自动根据使用的是hasmany还是hasone加上相应的all(), one()。
2、使用with(), joinwith() 查询时,如果在模型中定义hasmany,hasone方法时加上了all(),on河南农业大学分数线e(),程序会报错。
本文发布于:2023-04-07 16:39:07,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/ffc843a5a2aa2175d7a97f775ffc5fc1.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:Yii2中多表关联查询.doc
本文 PDF 下载地址:Yii2中多表关联查询.pdf
留言与评论(共有 0 条评论) |