【问题标题】:How to show relational data in yii2如何在yii2中显示关系数据
【发布时间】:2018-04-22 16:47:08
【问题描述】:

我无法理解关系在 yii 2 中的运作方式

我在 mysql 数据库中有 2 个表,作者和书。

book 有一个名为 author 的列,它通过外键链接到 author 表的 id。

我已经使用 gii 生成了 CRUD,我希望作者姓名出现在列表视图中,以及作者姓名的下拉列表中的创建和更新视图中。

但即使在列表视图中,我似乎也无法使关系正常工作。

这是我的代码

图书模型:

<?php

namespace app\models;

use Yii;
use app\models\Author;

/**
 * This is the model class for table "book".
 *
 * @property integer $id
 * @property string $name
 * @property integer $author
 */
class Book extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'book';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'author'], 'required'],
            [['author'], 'integer'],
            [['name'], 'string', 'max' => 11]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'author' => 'Author',
        ];
    }

    public function getAuthor()
    {
        return $this->hasOne(Author::className(), ['id' => 'author']);
    }
}

图书搜索模型:

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Book;

/**
 * BookSearch represents the model behind the search form about `app\models\Book`.
 */
class BookSearch extends Book
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'author'], 'integer'],
            [['name'], 'safe'],
        ];
    }

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

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Book::find();
        $query->joinWith('author');

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

        var_dump($dataProvider);
        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,
            'author' => $this->author,
        ]);

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

        return $dataProvider;
    }
}

另外,这里是视图文件:

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\BookSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Books';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="book-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Book', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

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

            'id',
            'name',
            [
                'attribute' => 'author',
                'value'     => 'author.name',
            ],

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

</div>

作者模型:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "author".
 *
 * @property integer $id
 * @property string $name
 */
class Author extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'author';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['name'], 'string', 'max' => 200]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
        ];
    }


}

我想我可能需要在作者/作者搜索模型中的某个地方进行更改。

谁能帮忙

谢谢

【问题讨论】:

  • 你应该阅读这个:yiiframework.com/doc-2.0/…
  • [ 'attribute'=&gt;'author', 'value'=&gt;$model-&gt;author-&gt;name ]
  • 也发布您的作者模型代码。
  • @MuhammadShahzad $model 未定义
  • 您是否在视图小部件中尝试过:'author.name'?

标签: php mysql yii2


【解决方案1】:

您还可以使用匿名函数的值将列添加到网格视图,如http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html#$value-detail 所述。例如,您可以在 gridview 中显示这样的作者姓名:

<?= GridView::widget([
'dataProvider'=>$dataProvider,
'filterModel'=>$searchModel,
'columns'=>[
    [
        'attribute'=>'author.name',
        'value'=>function ($model, $key, $index, $column) {
            return $model->author->name;
        },
    ],
    //...other columns
]);
?>

您也可以像这样返回一个指向作者详细视图的 html 链接:

//...
'columns'=>[
    [
        'attribute'=>'author',
        'value'=>function ($model, $key, $index, $column) {
            return Html::a($model->author->name, ['/author/view', 'id'=>$model->author->id]);
        },
    ],
    //...
],
//...

【讨论】:

    【解决方案2】:

    您可以使用关系名称访问任何 crud 视图文件中的关系表数据。 $model->relName->attribute_name.

    您可以通过以下方式访问gridview中的关系表数据:

    <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        [
            'attribute' => 'author',
            'value'=>'author.author_name', //relation name with their attribute
        ]
    ],
    

    ]);

    【讨论】:

      【解决方案3】:

      首先,您的模型中需要一个 get 函数,但您有。

      这是:

      public function getAuthor()
      {
          return $this->hasOne(Author::className(), ['id' => 'author']);
      }
      

      现在你只需要再做一件事。

      转到索引文件、GridView 和列。

      将此写入列:

      [
           'attribute' => 'author',
            'value' => 'author.name',
      ],
      

      值中,第一个参数是你的Get函数,命名为:getAuthor,在你的列名后面加上.

      【讨论】:

        【解决方案4】:

        您好,在您的图书搜索模式下,请像这样添加以下代码。

        $query->joinWith(array('author'));
        $query->andFilterWhere(['id' => $this->id,])
        ->andFilterWhere(['like', 'author.author_name', $this->author]);
        

        在您的视图文件中,请使用下面给定的代码,下面的代码用于网格属性中的视图文件。

        [
                'attribute' => 'author',
                'value' => 'author.name',
        ]
        

        我希望这会对你有所帮助。我希望作者表中的名称存储在名称列中。

        【讨论】:

        • $this-&gt;id 为空,所以这不起作用。还是谢谢
        • @TEster 请尝试在安全的规则数组中添加 id 字段它可能会帮助您喜欢这样 [['id','name'], 'safe']
        • 还是没有运气。我已将上述内容添加到视图文件中。现在这是我在 BookSearch 中的规则方法` public function rules() { return [ [['id', 'author'], 'integer'], [['id', 'name'], 'safe'], ] ; }`
        • @ TEster 正如你所说的 $this->id 为 null 意味着这是来自你的书表 ID,如果它在主键中尝试打印该 $this->id 的值。跨度>
        【解决方案5】:

        这对我有用 - 在 BookSearch 模型中:

        public function search($params)
        {
        
            $dataProvider = new \yii\data\SqlDataProvider([
                'sql' => 'SELECT book.id as id ,book.author_fk, book.name as book_name , author.name as author_name' . 
                            ' FROM book ' .
                            'INNER JOIN author ON (book.author_fk = author.id) '
            ]);
        
        
            $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;
            }
        
        
        
            return $dataProvider;
        }
        

        现在唯一的问题是让 ActionColumn 正常工作,它们当前链接到错误的 ID,请帮助任何人。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-06-11
          • 2015-03-31
          • 2020-08-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-02
          • 2016-07-13
          相关资源
          最近更新 更多