数据库设计: 通过订单查询客户与书籍,在透过书籍查询作者从而实现简易的多表关联

1 客户表Customer   (id  customer_name)
2 订单表Order      (id  order_name  customer_id   book_id)
3 书籍表book       (id  book_name   author_id)
4 作者表author     (id  author_name)

目标:通过订单表对客户表的customer_name,图书表的book_name,作者表的author_name进行数据关联与查询。例:

第一步获取数据:分别在模型层设立数据表关联      hasOne一对一关系   hasMany一对多关系

在order模型下关联customer_id与book_id,在book模型下关联author_id。例:

public function getCustomer()
{
//同样第一个参数指定关联的子表模型类名   
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}

在order/index.php  GridView中添加显示数据

'columns' => [
            'order_name',
            [
                'label'=>'客户名',
                'attribute'=>'customer_name',
                'value'=>'customer.customer_name'
            ],
            [
                'label'=>'书名',
                'attribute'=>'book_name',
                'value'=>'book.book_name'
            ],
            [
                'label'=>'作者名',
                'attribute'=>'author_name',
                'value'=>'book.author.author_name'
            ],
        ],

第二步创建查询

在models/OrderSearch.php中创建所需查询的字段

public $customer_name;
public $book_name;
public $author_name;

在rules中加上safe。

[['order_name','customer_name','book_name','author_name'], 'safe'],

在search中创建joinWith优化表查询,循环sql查询->一条sql查询
无条件关联表用with,有条件则用joinwith

 1  public function search($params)
 2     {   $this->load($params);
 3         $query = Order::find();
      //book.author 为通过book表的author_id获取author表的数据
4 $query->joinWith(['customer','book','book.author']);
      //andFilterWhere当一个值为 null、空数组、空字符串或者一个只包含空白字符时,那么它将被判定为空值。
5 $query->andFilterWhere(['order_name'=>$this->order_name]); 6 $query->andFilterWhere(['like','customer.customer_name', $this->customer_name]); 7 $query->andFilterWhere(['like','book.book_name', $this->book_name]); 8 $query->andWhere(['like','author.author_name', $this->author_name]); 9 $dataProvider = new ActiveDataProvider([ 10 'query' => $query, 11 ]); 12 $dataProvider->getModels(); 13 return $dataProvider; 14 }

 

posted on 2021-08-10 15:46  狐槑芸芽  阅读(76)  评论(0)    收藏  举报