如何在yii2中显示关系数据 [英] How to show relational data in yii2
问题描述
我无法理解 yii 2 中的关系是如何工作的
我在 mysql 数据库中有 2 个表,作者和书籍.
book 有一个名为 author 的列,它通过外键链接到 author 表的 id.
我已经使用 gii 生成了 CRUD,我希望作者姓名出现在列表视图中,以及创建和更新视图中作者姓名的下拉菜单中.
但即使在列表视图中,我似乎也无法使关系正常工作.
这是我的代码
图书模型:
11]];}/*** @inheritdoc*/公共函数attributeLabels(){返回 ['id' =>'ID','名称' =>'姓名','作者' =>'作者',];}公共函数 getAuthor(){返回 $this->hasOne(Author::className(), ['id' => 'author']);}}
图书搜索模型:
joinWith('author');$dataProvider = new ActiveDataProvider(['查询' =>$查询,]);var_dump($dataProvider);如果 (!$this->validate()) {//如果您不想在验证失败时返回任何记录,请取消注释以下行//$query->where('0=1');返回 $dataProvider;}$query->andFilterWhere(['id' =>$this->id,'作者' =>$this->作者,]);$query->andFilterWhere(['like', 'name', $this->name]);返回 $dataProvider;}}
此外,这是视图文件:
title = '书籍';$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(['数据提供者' =>$数据提供者,'过滤器模型' =>$搜索模型,'列' =>[['类' =>'yii\grid\SerialColumn'],'ID','姓名',['属性' =>'作者','价值' =>'作者名',],['类' =>'yii\grid\ActionColumn'],],]);?>
作者模型:
200]];}/*** @inheritdoc*/公共函数attributeLabels(){返回 ['id' =>'ID','名称' =>'姓名',];}}
我想我可能需要更改作者/作者搜索模型中的某些地方.
有人可以帮忙吗
谢谢
您还可以使用匿名函数的值向 gridview 添加列,如下所述 http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html#$value-detail.例如,您可以在 gridview 中像这样显示作者姓名:
= GridView::widget(['dataProvider'=>$dataProvider,'filterModel'=>$searchModel,'列'=>[['属性'=>'作者.name','值'=> 函数($model,$key,$index,$column){返回 $model->author->name;},],//...其他列]);?>
您还可以像这样返回一个指向作者详细信息视图的 html 链接:
//...'列'=>[['属性'=>'作者','值'=> 函数($model,$key,$index,$column){return Html::a($model->author->name, ['/author/view', 'id'=>$model->author->id]);},],//...],//...
I'm having trouble understanding how relations work in yii 2
I have 2 tables in a mysql database, author and book.
book has a column named author which links to the id of the author table via foreign key.
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.
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:
<?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.
Can someone help
thanks
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. For example you can show an author's name like this in a 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:
//...
'columns'=>[
[
'attribute'=>'author',
'value'=>function ($model, $key, $index, $column) {
return Html::a($model->author->name, ['/author/view', 'id'=>$model->author->id]);
},
],
//...
],
//...
这篇关于如何在yii2中显示关系数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!