• 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 }

     效果图为:

  • 相关阅读:
    python模拟shell
    10.LIKE 操作符
    9.TOP 子句--mysql limit
    8.INSERT INTO 语句 UPDATE 语句
    7.ORDER BY 子句
    6.AND & OR 运算符
    5.WHERE 子句
    4.SELECT DISTINCT 语句
    3.SELECT 语句
    2.sql分类
  • 原文地址:https://www.cnblogs.com/jacson/p/4759839.html
Copyright © 2020-2023  润新知