【问题标题】:Yii2 - show rows in common between two tablesYii2 - 显示两个表之间的共同行
【发布时间】:2017-07-25 06:00:12
【问题描述】:

我有两个表“Personal_data”和“Students”,Student 有 Personal_data。 我使用 Gii 为视图、控制器和模型生成代码,我需要在 GridView 中显示来自“Students”的所有“Personal_data”,但我无法得到它。

models/PersonalDataSearch.php 中的代码

public function search($params)
{
    $query = PersonalData::find()->joinWith('Students'])->all();

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

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        'id' => $this->id,
        'document' => $this->document,
        'telephone' => $this->telephone,
        'direction' => $this->direction,
        'sex' => $this->sex,
    ]);

    $query->andFilterWhere(['like', 'names', $this->names])
        ->andFilterWhere(['like', 'lastNames', $this->lastNames])
        ->andFilterWhere(['like', 'email', $this->email])
        ->andFilterWhere(['like', 'movile', $this->movile]);

       return $dataProvider;
}

来自控制器/PersonalDataController.php 的代码

public function actionIndex()
{
    $searchModel = new PersonalDataSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

来自views/personal-data/index.php的代码

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'names',
        'lastNames',
        'email:email',
        'movile',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

此视图最初显示来自所有注册人员的 Personal_data 表中的所有行,但我只想显示来自学生的 Personal_Data,我添加了这一行:

$query = PersonalData::find()->joinWith('Students'])->all();

我有这个错误:

PHP 致命错误 – yii\base\ErrorException

调用数组上的成员函数和FilterWhere()

我该如何解决这个问题?

【问题讨论】:

    标签: php yii2


    【解决方案1】:

    中删除-&gt;all()
    $query = PersonalData::find()->joinWith('Students'])->all();
    

    数据提供者负责从数据库中获取数据,您只需要构建查询(all() 正在获取数据)。只需一个查询,您就可以向其中添加过滤器,这样andFilterWhere() 就不会出现错误

    【讨论】:

    • Bizley 你是对的,删除 all() 方法,解决了错误,但 GridView 仍然显示“PersonalData”中的所有行。经过反复尝试,我添加了这个: $query = PersonalData::find() ->innerJoinWith('Students') ->where(['','Students.id','null']);现在我从“Students”那里得到所有“personal_data”,谢谢。
    • 为什么不反过来显示关系呢?学生->个人数据。
    • 我需要在 PersonalData 和 Student 中显示一些数据,但可以选择,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2021-01-01
    相关资源
    最近更新 更多