【问题标题】:Pagination with array in yii2yii2中的数组分页
【发布时间】:2016-05-31 22:09:44
【问题描述】:

我想在我的视图中使用分页,但我不知道如何与find() 方法结合使用。

获取页数可以正常工作,但它总是显示数据库中的所有值。我希望看到每页 15 cmets。

这是我的 ViewAction 控制器:

 public function actionView($id) {
     $query = UrComment::find()->where(['IsDeleted' => 0]);

     $pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
     return $this->render('view', [
            'model' => $this->findOneModel($id),
            'comment' => UrComment::findComment($id),
            'pagination'=> $pagination
     ]);
}

这就是我获得 cmets 的方式:

public static function findComment($id)
{
    if (($model = UrUser::findOne($id)) !== null) {
        $Id=$model->Id;
        $comment = UrComment::find()->where(['Rel_User' => $Id])->all();
        return $comment;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

我试过用这个:

public function actionView($id) {
    $query = UrComment::find()->where(['IsDeleted' => 0]);
    $pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>12]);
    $comment= UrComment::findComment($id);
    $comment->offset($pagination->offset)
        ->limit($pagination->limit)
        ->all();

    return $this->render('view', [
                'model' => $this->findOneModel($id),
                'comment' =>$comment,
                'pagination'=> $pagination
    ]);
}

但我收到此错误:

调用数组上的成员函数offset()

然后我在视图中显示:

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model backend\modules\users\models\UrUser */

$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
        <?=
        Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
                'method' => 'post',
            ],
        ])
        ?>
    </p>

    <?=
    DetailView::widget([
        'model' => $model,
        'attributes' => [
            'Id',
            'Name',
            'Surname',
            'BirthDate',
            'Login',
            'Email:email',
            ['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
            ['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
            ['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
            ['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
        ],
    ])
    ?>

Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>


    <?php foreach ($comment as $comm): ?>

     <?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comm->Id], ['class' => 'btn btn-primary']) ?>
        <?=
        Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comm->Id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
                'method' => 'post',
            ],
        ])
        ?>
            <p><?= $comm->Text ?></p>

    <hr>
    <?php endforeach; ?>
<?php
   echo \yii\widgets\LinkPager::widget([
    'pagination' => $pagination,
]);
?>

</div>
</div>    
</div>

如何使用分页限制UrComment::findComment($id)

编辑:

我想我理解你,我想我已经完成了你在回答中告诉我的一切,但现在我遇到了另一个问题。我只需要在视图 cmets 下显示 id view only this one 而不是所有 cmets。

这是我现在拥有的:

动作视图:

public function actionView($id) {
    $searchModel = new CommentSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    $dataProvider->query->andWhere(['IsDeleted' => 0]);
    $dataProvider->pagination->pageSize=15;

    return $this->render('view', [
                'model' => $this->findOneModel($id),
                'comment' => UrComment::findComment($id),
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
    ]);
}

评论搜索:

<?php

namespace backend\modules\users\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\UrComment;

class CommentSearch extends UrComment
{        
    public function rules() {
        return [
            [['Id'], 'integer'],
            [['Text'], 'safe'],           
        ];
    }

    public function scenarios() {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    public function search($params) {
        $query = UrComment::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'Id' => $this->Id,
            'Text' => $this->Text,                
        ]);

        $query->andFilterWhere(['like', 'Text', $this->Text]);

        return $dataProvider;
    }
}

查看:

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\widgets\ListView;
/* @var $this yii\web\View */
/* @var $model backend\modules\users\models\UrUser */

$this->title = $model->Name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Użytkownicy'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="ur-user-view">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a(Yii::t('app', 'Aktualizuj'), ['update', 'id' => $model->Id], ['class' => 'btn btn-primary']) ?>
        <?=
        Html::a(Yii::t('app', 'Usuń'), ['delete', 'id' => $model->Id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
                'method' => 'post',
            ],
        ])
        ?>
    </p>

    <?=
    DetailView::widget([
        'model' => $model,
        'attributes' => [
            'Id',
            'Name',
            'Surname',
            'BirthDate',
            'Login',
            'Email:email',
            ['attribute' => 'Rel_Sex', 'value' => (isset($model->relSex->Name)? $model->relSex->Name : "Nie wybrano")],
            ['attribute' => 'Rel_Language', 'value' => (isset($model->relLanguage->Name)) ? $model->relLanguage->Name : "Nie wybrano"],
            ['attribute' => 'Rel_Country', 'value' => (isset($model->relCountry->Name)) ? $model->relCountry->Name : "Nie wybrano"],
            ['attribute' => 'Rel_Category', 'value' => (isset($model->relUserCategory->Name)) ? $model->relUserCategory->Name : "Nie wybrano"],
        ],
    ])
    ?>
Komentarze użytkownika: <?= $model->Name.' '.$model->Surname;?><br><br>
<?php    
  echo ListView::widget([
   'dataProvider' => $dataProvider,
   'itemView' => 'comments',
   'viewParams' => ['comment' => $comment, 'model'=>$model],
]);
?>
</div>
</div> 
</div>

还有我的物品:

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model backend\modules\users\models\UrUser */


?> 
     <?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => $comment->Id], ['class' => 'btn btn-primary']) ?>
        <?=
        Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => $comment->Id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
                'method' => 'post',
            ],
        ])
        ?>
            <p><?= $comment->Text ?></p>

    <hr>

使用该代码,现在我在按钮编辑的此项中出现错误:

$comment->Id], ['class' => 'btn btn-primary']) ?>

试图获取非对象的属性

我不能在那里使用 foreach,因为我有重复的 cmets。是否应该在评论搜索或我的功能findComment(id)查询中更改某些内容?

有我的实际项目“cmets”,我想在其中显示 cmets 的文本以及用于编辑和删除评论的按钮。但这对我不起作用。我有:

使用未定义的常量 Id - 假定为“Id”

使用未定义的常量文本 - 假定为“文本”;

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model backend\modules\users\models\UrUser */


?> 
     <?= Html::a(Yii::t('app', 'Edytuj'), ['update-user-comment', 'id' => Id], ['class' => 'btn btn-primary']) ?>
        <?=
        Html::a(Yii::t('app', 'Usuń'), ['delete-comment', 'id' => Id], [
            'class' => 'btn btn-danger',
            'data' => [
                'confirm' => Yii::t('app', 'Jesteś pewien, że chesz usunąć tego użytkownika?'),
                'method' => 'post',
            ],
        ])
        ?>
            <p><?= Text ?></p>
    <hr>

【问题讨论】:

    标签: php view pagination yii2


    【解决方案1】:

    如果你使用 model 和 foreach 并不容易,请使用分页,因为分页如果基于 dataProvider 而不是直接用于 model ..

    基本上像您一样找到模型意味着直接处理数据,而分页不直接处理数据,而是使用 sql 查询从 db 中检索信息,让这些信息可用于小部件 .. 这就是dataProvider 执行 .. .. 然后我建议您使用像 ListView 这样的小部件,并根据使用基于 modelSearch 的 dataProvider 的查找来更改您的查询..

    public function actionView($id) {
        $searchModel = new UrCommentSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere(['IsDeleted' => 0]);
        $dataProvider->pagination->pageSize=15;
    
        return $this->render('view', [
            'model' => $this->findOneModel($id),
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    

    对于 view.php

    <?php 
    
    echo ' <h1>User :  ' .  $model->userName . '</h1>';
    
    echo '<h2>Comments</h2'>,
    
    echo ListView::widget([
    
       'dataProvider' => $dataProvider,
       'itemView' => '_comment',
    ]);
    

    其中 _comment 是您的评论布局的部分视图 .,.

    然后在 _comment.php 你可以简单地

    <?=$model->id;?> 
    <?=$model->text;?> 
    

    【讨论】:

    • 感谢您的评论。你让我进入这个解决方案,但我仍然不知道如何将属于用户的我的 cmets 转移到我显示这个 cmets 的评论(项目视图)中
    • 您可以同时传递(用于用户数据的 $model 和用于 cmets 的 $dataProvider ),然后在适当的顶部区域显示模型,并在 ListView 中显示 cmets .. 我以这种方式更新了一些建议的答案..
    • 但是 $model 关注用户表。你写了 tihs itemView 但我不知道我应该在这个 _comment 中写什么来显示这个 cmets。我应该在哪里使用这个 $dataProvider 来在 $dataProvider 中显示评论或这个查询
    • 你有空的时候可以看看我最后的代码吗?因为当我使用文本时;它对我没有用。它不能用 dataProvider 传达吗?我搜索示例但我失败了。从查询中显示 cmets 的方法是什么,因为简单的 Id(在数据库中的第一个字母很大,因为我首先有大字母)或简单的文本不适合我,我不知道为什么
    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多