YII2 AR联查 搜索联查 分页联查

YII2 AR联查 搜索联查 分页联查
官方 教程
PHP 官网
开始之前 联查遇到各种问题 然后搜索一大把资料 有用的没几个
说一下 下面 粗心遇到的坑

  1. 模型层 return $this->hasOne(Ncs::class, ['id' => 'n_id']);
    要注意这个 hasOne , 不是hasMany

    如果视图层是 · GridView::widget· 渲染的话 使用 方法名.属性

    DEMO

public function getManager()
{
return $this->hasOne(Ncs::class, [‘id’ => ‘n_id’]);
}

这里 方法名是 Manage
在视图层 manager.title 使用

视图.

<?php 
use yii\grid\GridView;
use common\helpers\Html;
use common\helpers\ImageHelper;
$this->title = '关于 Aubot';
$this->params['breadcrumbs'][] = ['label' => $this->title];

 ?>
 <div class="row">
    <div class="col-xs-12">
        <div class="box">
            <div class="box-header">
                <h3 class="box-title"><?= $this->title; ?></h3>
                <div class="box-tools">
                    <?= Html::create(['ajax-edit'], '创建', [
                        'data-toggle' => 'modal',
                        'data-target' => '#ajaxModal',
                    ])?>
                </div>
            </div>
            <div class="box-body table-responsive">
                <?= GridView::widget([
                    'dataProvider' => $dataProvider,
                    'filterModel' => $searchModel,
                    //重新定义分页样式
                    'tableOptions' => ['class' => 'table table-hover'],
                    'columns' => [
                        [
                            'class' => 'yii\grid\SerialColumn',
                        ],
                       
                        [
                            'attribute' => 'id',
                            'filter' => false, //不显示搜索框
                        ],
                        'manager.title',
                        'title',
                        [
                            'attribute' => 'status',
                            'format' => 'raw',
                            'headerOptions' => ['class' => 'col-md-1'],
                            'value' => function ($model, $key, $index, $column){
                                return Html::whether($model['status']);
                            }
                        ],
                        [
                                'attribute' => 'sort',
                                'format' => 'raw',
                                'headerOptions' => ['class' => 'col-md-1'],
                                'value' => function ($model, $key, $index, $column){
                                    return  Html::sort($model->sort);
                                }
                        ],
                      
                        [
                            'header' => "操作",
                            'class' => 'yii\grid\ActionColumn',
                            'template'=> '{edit} {status} {destroy}',
                            'buttons' => [
 
                                'edit' => function ($url, $model, $key) {
                                    return Html::edit(['edit', 'id' => $model->id]);
                                },
                                'status' => function ($url, $model, $key) {
                                    return Html::status($model->status);
                                },
                                'destroy' => function ($url, $model, $key) {
                                    return Html::delete(['destroy','id' => $model->id]);
                                },
                            ],
                        ],
                    ],
                ]); ?>
        </div>
    </div>
</div>

控制器

<?php
namespace backend\modules\ncs\controllers;

use Yii;
use common\models\common\SearchModel;
use common\enums\StatusEnum;
use common\models\ncs\About;
use common\models\ncs\Ncs;
use backend\controllers\BaseController;
use common\components\Curd;
use yii\data\ActiveDataProvider;
use common\helpers\ArrayHelper;
use yii\base\Model;


/**
 * Class ActionLogController
 * @package backend\modules\Ncs\controllers
 * @author lijie
 */
class AboutController extends BaseController
{   

    use Curd;

    /**
     * @var \yii\db\ActiveRecord
     */
    public $modelClass = About::class;


    /**
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionIndex()
    {    
        $searchModel = new SearchModel([
            'model' => About::class ,
            'scenario' => 'default',
             // 'relations' => ['manager' =>['title']], 
            'partialMatchAttributes' => ['n_id','title', 'text',], // 模糊查询
            'defaultOrder' => [
                 'id'=>SORT_DESC,'sort'=>SORT_DESC,
            ],
            'pageSize' => $this->pageSize,
        ]);
            $dataProvider = $searchModel->search(['SearchModel'=>Yii::$app->request->queryParams]);
            // $dataProvider->query->select('a.*,c.*')->from('rf_navigation_about AS a')->leftJoin('rf_navigation_content AS c', '`c`.`id` = `a`.`n_id`')->all();
            // $dataProvider->query->with('manager')->all();
               // print_r($dataProvider) ; die();
        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }
     /**
    * @ description   article_p_id  父级ID 排序
    */
    static function article_p_id($p_id,$arr,$va){
    static  $statuc =array();
    static  $children ="├";
    // $statuc[$p_id] = $va;
        if ($va== 0) {
            $statuc =array();
        }
        foreach ($arr as $key => $value) {
        if ($p_id == $value['pid']) {
            $temp ="";
            for ($i=0; $i < substr_count($children,'├'); $i++) { 
                $temp.="  ";
            }
            $value['title'] = $temp.'├──'.$value['title'];

            $children.="├";
            $statuc[] = $value;
            self::article_p_id($value['id'],$arr,1);
            $children ="├";
        }
    }
    return $statuc;
   }
    /**
     * 获取下拉
     *
     * @param string $id
     * @return array
     */
    public function getDropDownList($id = '')
    {
        $list = $this->modelClass::find()
            ->where(['>=', 'status', StatusEnum::DISABLED])
            // ->andFilterWhere(['<>', 'id', $id])
            ->select(['id', 'title', 'pid', 'level'])
            ->orderBy('pid asc, sort asc')
            ->asArray()
            ->all();
       $p_id = array();
      $not_p = array(); //除了0 之外
      foreach ($list as $key => $value) {
         if ($value['pid']==0) {
            $p_id[]  = $value;
            $not_p[] = self::article_p_id($value['id'],$list,0);
         }
      }
    $return_arr =array();
        foreach ($p_id as $key => $value) {
        $return_arr[$value['id']] = $value['title'];
            foreach ($not_p[$key] as $k => $va) {
                $return_arr[$va['id']] = $va['title'];
            }
        }
    // $temp_id = array_column($return_arr,'id');
    // $temp_title = array_column($return_arr,'title');
    $models = ArrayHelper::itemsMerge($list);
    //return ArrayHelper::map(ArrayHelper::itemsMergeDropDown($models), 'id', 'title');
    return  ArrayHelper::merge([0 => '顶级菜单'], $return_arr);
        
    }


    /**
     * 编辑/创建
     *
     * @return mixed|string|\yii\web\Response
     * @throws \yii\base\ExitException
     */
    public function actionAjaxEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', ''); //获取ID 
        $model = $this->findModel($id);
        $model->id = $request->get('id', null) ?? $model->id; // 父id
        $model->pid = $request->get('pid', null) ?? $model->pid; // 分类id
        $model->url = $request->post('url', null) ?? $model->url; // 路由
        $model->icon = $request->post('icon', null) ?? $model->icon; // 图标
        $model->sort = $request->post('sort', null) ?? $model->sort; // 排序
        // $model->level =  $model->level+1; // 分类id
        $model->params = unserialize($model->params);
        // ajax 校验
        $this->activeFormValidate($model);
        if ($model->load($request->post())) {
            $model->params = serialize($model->params);
            return $model->save() //修改OK
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        // print_r($this->getDropDownList()); die();

        return $this->renderAjax('ajax-edit', [
            'model' => $model,
            // 'cates' => Yii::$app->services->sysMenuCate->getMapDefaultMapList(),
            'menuDropDownList' => $this->getDropDownList($id),
        ]);
    }
 

    /**
     * 行为日志详情
     *
     * @param $id
     * @return string
     */
    public function actionView($id)
    {
        $model = ActionLog::find()
            ->where(['id' => $id])
            ->one();

        return $this->renderAjax($this->action->id, [
            'model' => $model,
        ]);
    }
    /**
     * 返回模型
     *
     * @param $id
     * @return \yii\db\ActiveRecord
     */
    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || empty(($model = $this->modelClass::findOne($id)))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }

        return $model;
    }
}

模型

<?php
namespace common\models\ncs;

use common\behaviors\MerchantBehavior;

/**
* This is the model class for table "rf_navigation_content".
*
* @property int $id 主键
* @property string $n_id 内容ID
* @property string $title 标题
* @property string $text  neir 内容
* @property string $temp 缓存
* @property string $created_at 创建时间
* @property string $updated_at 修改时间
* @property string $sort 排序
* @property string $status 状态
 */
class About extends \common\models\common\BaseModel
{
 

    /**
     * {@inheritdoc}
     */
    public $class_name;
    public static function tableName()
    {
        return '{{%navigation_about}}';
    }
    
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [

            [['id', 'n_id', 'sort', 'status', 'created_at', 'updated_at'], 'integer'],
            [['title'], 'string'],
            [['text'], 'string',],
            [['temp'], 'string'],
            // [['sort'], 'string'],
            // [['pid'], 'string', 'max' => 206],
       
            // [['remark'], 'string', 'max' => 1000],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'n_id' => '所属ID',
            'text' => '内容',
            'type' => '类型',
            'status' => '是否可见',
            'created_at' => '创建时间',
            'updated_at' => '修改时间',
            'sort' => '排序',
            'temp' => '缓存 ',
            'level'=>'级别',
            
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getManager()
    {
        return $this->hasOne(Ncs::class, ['id' => 'n_id']);
    }
     /**
     * @return \yii\db\ActiveQuery
     *
     */

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值