Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

sorting - Yii2 Related table filter and sort with Grid View

I had this questions part by part and solve it now so I want to share maybe someone will use it. I have 4 models: Users,Certificate, Products, Autority. The main will be Users, from users Id we see certificate, from certificate Id we si the product id, from product id we see the autority. I solve it in one way so maybe someone can tell me if it is good or there are some other ways to do it. This will be step by step description. :)

1)In models set links between tables (hasOne, hasMany) (this have to be in each model which have connection with next model)

public function getCertificate()
{   return  $this->hasOne(Certificate::className(),['id_customer' =>'id']); } 

2) in the main table searchmodel call connection and in connection use joinWith to define the relation of your database, example:

$query = Users::find()
    -> where (['USERSTB.id_user' =>Yii::$app->session->get('user.idcustomer') ])
            ->joinWith('Certificate')
            ->joinWith('Certificate.Products')
            ->joinWith('Certificate.Products.Autority');

3) add to searchmodel public variables for each field in the attached tables, for example:

public $cert_description;
public $cert_autority_description;
public $cert_actdate;
public $cert_expdate;  
public $cert_domain;   

4) add variable names in rules() and to field safe, for example:

public function rules()
{   return [ [ ['cert_domain','cert_description','cert_autority_description','cert_actdate','cert_expdate'], 'safe'],      ];  }

5)adding sort in to search method, use it under declaration of $dataProvider, for example:

$dataProvider->sort->attributes['cert_description'] = [
    'asc' => ['products.description' => SORT_ASC],
    'desc' => ['products.description'=> SORT_DESC], ];  

6) adding search query using andFilterWhere:

 ->andFilterWhere(['like', 'products.description', $this->cert_description])

7)And finally display data in Index GridView, on attributes that you want to view, for example:

 [  
    'attribute' => 'cert_description',  // !!! important to matches the name attribute
    'label'=>'Certificate',
    'value'=> 'Certificate.Products.description', 
],

If there is any other better method or different one I will be glad to see it. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...