zoukankan      html  css  js  c++  java
  • YII的关联查询

    先看数据表中的关系是怎样的:

    customer表中的关系如下:

    order中的表为:

    先在customer中获得order的数据,并与之关联,在 helloController.php 中,代码如下

     1 <?php
     2 namespace appcontrollers;
     3 use yiiwebController;
     4 use appmodelsCustomer;
     5 use appmodelsOrder;
     6 
     7 class HelloController extends Controller {
     8     public function actionIndex()
     9     {
    10        $customer = Customer::find()->where(['name'=>'zhangsan'])->one();
    11 //        $orders=$customer->getOrders();//getOrders()是在cunstomer.php中的函数,与下面代码效果一致
    12         $orders = $customer->orders;//只用orders而不声明getOrders()是因为程序会自动使用__get()方法,调用Customer.php中的getOrders()方法。
    13         print_r($orders);
    14     }
    15 }

    在 appmodelsCustomer.php 中的代码为:

     1 <?php
     2 namespace appmodels;
     3 
     4 use yiidbActiveRecord;
     5 class Customer extends ActiveRecord{
     6     public function getOrders(){
     7         $orders = $this->hasMany(Order::className(),['customer_id'=>'id'])->asArray();//Order::className()等同于'appmadelsOrder'是使用Order.php下面的方法,其中'customer_id'='id'中的id是customer表中id,而不是order表中的id
     8         return $orders;
     9     }
    10 }

    在 appmodelsOrder.php 中的代码为:

    1 <?php
    2 namespace appmodels;
    3 
    4 use yiidbActiveRecord;
    5 class Order extends ActiveRecord{
    6 
    7 }

    程序打印出的效果如图:

    然后在order中获得customer中的数据,再与之关联。

    helloController中的代码为:

     1 <?php
     2 namespace appcontrollers;
     3 use yiiwebController;
     4 use appmodelsCustomer;
     5 use appmodelsOrder;
     6 
     7 class HelloController extends Controller {
     8     public function actionIndex()
     9     {
    10         $order = Order::find()->where(['id'=>1])->one();
    11         $customer = $order->customer;
    12         print_r($customer);
    13     }
    14 }

    order.php中的代码:

     1 <?php
     2 namespace appmodels;
     3 
     4 use yiidbActiveRecord;
     5 class Order extends ActiveRecord{
     6     public function getCustomer() {
     7        $customer= $this->hasOne(Customer::className(),['id'=>'customer_id'])->asArray();
     8         return $customer;
     9     }
    10 }

    然后在customer.php中的代码为:

    1 <?php
    2 namespace appmodels;
    3 
    4 use yiidbActiveRecord;
    5 class Customer extends ActiveRecord{
    6 
    7 }

     效果图为:

  • 相关阅读:
    <Graph> Topological + Undirected Graph 310 Union Find 261 + 323 + (hard)305
    <Topological Sort> ( 高频, hard) 269
    <Stack> (高频)394 ( 高频)224
    <DFS & BFS> 286 339 (BFS)364
    <Matrix> 311 378
    <Binary Search> 81 (高频)34 (很难hard, 高频)315 (hard)354
    <LinkedList> 369 (高)143 (第二遍)142 148
    <DP> (高频)139 375 374 (DP hard)312
    <BackTracking> permutation 254 47 60
    <Tree> 298 250 366 199(高频) 98(高频)
  • 原文地址:https://www.cnblogs.com/jacson/p/4759839.html
Copyright © 2011-2022 走看看