[英]How to show relational data in yii2
I'm having trouble understanding how relations work in yii 2 我无法理解关系如何在yii 2中发挥作用
I have 2 tables in a mysql database, author and book. 我在mysql数据库,作者和书中有2个表。
book has a column named author which links to the id of the author table via foreign key. book有一个名为author的列,它通过外键链接到author表的id。
I've generated CRUD using gii, and I want the author name to appear in the list view, as well as dropdowns for the author name in the create and update views. 我使用gii生成了CRUD,我希望作者名称出现在列表视图中,以及创建和更新视图中作者姓名的下拉列表。
But I cant seem to get the relation working even in the list view. 但我似乎无法使关系工作,即使在列表视图中。
Here's my code 这是我的代码
Book Model: 书籍型号:
<?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']);
}
}
BookSearch Model: BookSearch模型:
<?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;
}
}
Also, here's the view file: 另外,这是视图文件:
<?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>
Author Model: 作者型号:
<?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',
];
}
}
I think I may have to change something somehwhere in the author/authorSearch model. 我想我可能不得不在作者/ authorSearch模型中改变某些地方。
Can someone help 有人可以帮忙吗
thanks 谢谢
You can access relation table data in any crud view file using their relation name. 您可以使用其关系名称访问任何crud视图文件中的关系表数据。 $model->relName->attribute_name. $模型 - > relName->属性名称。
And You can access relation table data in gridview at following way : 您可以通过以下方式访问gridview中的关系表数据:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'author',
'value'=>'author.author_name', //relation name with their attribute
]
],
]); ]);
You can also add columns to a gridview with value from an anonymous function as described here http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html# $value-detail. 您还可以使用匿名函数的值向gridview添加列,如http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html# $ value-detail所述。 For example you can show an author's name like this in a gridview: 例如,您可以在gridview中显示这样的作者姓名:
<?= GridView::widget([
'dataProvider'=>$dataProvider,
'filterModel'=>$searchModel,
'columns'=>[
[
'attribute'=>'author.name',
'value'=>function ($model, $key, $index, $column) {
return $model->author->name;
},
],
//...other columns
]);
?>
you can also return a html-link to the detail-view of an author like this: 你也可以返回一个html链接到这样的作者的详细视图:
//...
'columns'=>[
[
'attribute'=>'author',
'value'=>function ($model, $key, $index, $column) {
return Html::a($model->author->name, ['/author/view', 'id'=>$model->author->id]);
},
],
//...
],
//...
First you need a get function in your model, but you have. 首先,你需要在你的模型中使用get函数,但是你有。
This is : 这是 :
public function getAuthor()
{
return $this->hasOne(Author::className(), ['id' => 'author']);
}
Now you just need do one more thing. 现在你只需再做一件事了。
Go to the index file, and to GridView, and columns. 转到索引文件,GridView和列。
Write this into columns: 将此写入列:
[
'attribute' => 'author',
'value' => 'author.name',
],
In the value, the first parameter is your Get function, what named is : getAuthor, and .
在值中,第一个参数是Get函数,命名为:getAuthor,和.
after your column name. 在您的列名称之后。
Hello in your BookSearch Mode please add below code like this. 您好,在BookSearch模式下,请添加以下代码。
$query->joinWith(array('author'));
$query->andFilterWhere(['id' => $this->id,])
->andFilterWhere(['like', 'author.author_name', $this->author]);
And in your view file please use below given code below code is for view file inside grid attrubute. 并在您的视图文件中使用下面给出的代码下面的代码是网格attrubute内的视图文件。
[
'attribute' => 'author',
'value' => 'author.name',
]
i hope this will helps you. 我希望这会对你有所帮助。 and i hope in author table name is stored in name column. 我希望作者表名存储在名称列中。
This worked for me - inside the BookSearch Model: 这对我有用 - 在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;
}
Only issue now is getting the ActionColumn to work correctly, they're currently linking to the wrong IDs, help anyone. 现在唯一的问题是让ActionColumn正常工作,他们目前正在链接到错误的ID,帮助任何人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.