Показать связанные данные в представлении Yii 2

Я новичок в Yii 2, и я создаю систему инвентаризации для библиотеки моей школы, но у меня была проблема.

Во-первых, у меня есть такое отношение:

введите описание изображения здесь

Я хочу показать все adqs (уникальный номер для каждой книги — таким образом, нам не нужно снова захватывать книгу для каждой копии) книги в его представлении, но только adqсвязанные с книгой id очевидно внизу.

введите описание изображения здесь

Мой взгляд:

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\grid\GridView;

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

$this->title = $model->lib_titulo;
$this->params['breadcrumbs'][] = ['label' => 'Libros', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="libros-view">

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

<p>
<?= Html::a('Modificar', ['update', 'id' => $model->lib_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Borrar', ['delete', 'id' => $model->lib_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<div class="row" align="center">
<?php
if ($model->lib_image_web_filename!='') {
echo '<br /><p><img width="500" src="'.Url::to('@web/', true). '/uploads/libros/'.$model->lib_image_web_filename.'"></p>';
}
?>
</div>
<div class="row" style="text-align: center;
font: normal normal bold 15px/1 'lato';
color: rgba(7,7,7,1);
text-align: center;
">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'lib_id',
'lib_titulo',
'lib_autor',
//'lib_edicion',
'editorialNombre',
'ubicacionNombre',
'lib_isbn',
'lib_clasificacion',
'lib_seccion',
//'lib_image_src_filename',
//'lib_image_web_filename',
],
]) ?>
</div>


</div>

Мой контроллер (LibrosController):

<?php

namespace backend\controllers;

use Yii;
use app\models\Libros;
use app\models\LibrosSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
* LibrosController implements the CRUD actions for Libros model.
*/
class LibrosController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}

/**
* Lists all Libros models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new LibrosSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

/**
* Displays a single Libros model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/

public function actionCreate()
{
$model = new Libros();

if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
}  else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}

/**
* Updates an existing Libros model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);

if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = explode(".", $image->name);
$ext_final = end($ext);
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext_final}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
}  else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}

/**
* Deletes an existing Libros model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();

return $this->redirect(['index']);
}

/**
* Finds the Libros model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Libros the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Libros::findOne($id)) !== null) {
return $model;
}

throw new NotFoundHttpException('The requested page does not exist.');
}
}

Моя модель (Libros.php):

<?php

namespace app\models;

use Yii;

/**
* This is the model class for table "libros".
*
* @property int $lib_id
* @property string $lib_titulo
* @property string $lib_autor
* @property string $lib_edicion
* @property int $lib_ubi
* @property int $lib_editorial_id
* @property string $lib_isbn
* @property string $lib_clasificacion
* @property string $lib_seccion
* @property string $lib_image_src_filename
* @property string $lib_image_web_filename
*
* @property Adq[] $adqs
* @property Editorial $libEditorial
* @property Ubicacion $libUbi
* @property LibrosCarreras[] $librosCarreras
* @property Carreras[] $licCarreras
*/
class Libros extends \yii\db\ActiveRecord
{
const PERMISSIONS_PRIVATE = 10;
const PERMISSIONS_PUBLIC = 20;
public $image;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'libros';
}

/**
* @inheritdoc
*/
public function rules()
{
return [
[['lib_titulo', 'lib_autor', 'lib_ubi', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'required'],
[['lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo'], 'string', 'max' => 120],
[['lib_autor', 'lib_clasificacion'], 'string', 'max' => 64],
//[['lib_edicion'], 'string', 'max' => 3],
[['lib_isbn'], 'string', 'max' => 32],
[['lib_seccion'], 'string', 'max' => 2],
[['lib_editorial_id'], 'exist', 'skipOnError' => true, 'targetClass' => Editorial::className(), 'targetAttribute' => ['lib_editorial_id' => 'edi_id']],
[['lib_ubi'], 'exist', 'skipOnError' => true, 'targetClass' => Ubicacion::className(), 'targetAttribute' => ['lib_ubi' => 'ubil_id']],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 100],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
[['image'], 'file', 'maxSize'=>'1000000'],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 255],        ];
}

/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'lib_id' => 'ID',
'lib_titulo' => 'Titulo',
'lib_autor' => 'Autor',
//'lib_edicion' => 'Edicion',
'lib_editorial_id' => 'Editorial',
'lib_isbn' => 'ISBN',
'lib_clasificacion' => 'Clasificacion',
'lib_ubi' => 'Ubicacion',
'lib_seccion' => 'Seccion',
'image' => 'Captura',
'lib_image_src_filename' => Yii::t('app', 'Nombre de Archivo'),
'lib_image_web_filename' => Yii::t('app', 'Nombre del Directorio'),
'editorialNombre' => 'Editorial',
'ubicacionNombre' => 'Ubicacion',
];
}

/**
* @return \yii\db\ActiveQuery
*/
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}

/**
* @return \yii\db\ActiveQuery
*/


/**
* @return \yii\db\ActiveQuery
*/
public function getLibrosCarreras()
{
return $this->hasMany(LibrosCarreras::className(), ['lic_libros_id' => 'lib_id']);
}

/**
* @return \yii\db\ActiveQuery
*/

public function getEditorial0()
{
return $this->hasOne(Editorial::className(), ['edi_id' => 'lib_editorial_id']);
}
public function getEditorialNombre()
{
return $this->editorial0->edi_nombre;
}

public function getLibUbi()
{
return $this->hasOne(Ubicacion::className(), ['ubil_id' => 'lib_ubi']);
}

public function getUbicacionNombre()
{
return $this->libUbi->ubil_nombre;    }
}

Моя модель поиска (LibrosSearch.php):

<?php

namespace app\models;

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

/**
* LibrosSearch represents the model behind the search form of `app\models\Libros`.
*/
class LibrosSearch extends Libros
{
public $editorialNombre;
public $ubicacionNombre;

/**
* @inheritdoc
*/
public function rules()
{
return [
[['lib_id', 'lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo', 'lib_autor', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'safe'],
[['editorialNombre'],'safe'],
[['ubicacionNombre'],'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 = Libros::find();

// add conditions that should always apply here

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

$dataProvider->setSort([
'attributes'=>[
'editorialNombre'=>[
'asc'=>['editorial.edi_nombre'=>SORT_ASC],
'desc'=>['editorial.edi_nombre'=>SORT_DESC],
'label'=>'Editorial Nombre'
]
]
]);

$dataProvider->setSort([
'attributes'=>[
'ubicacionNombre'=>[
'asc'=>['ubicacion.ubil_nombre'=>SORT_ASC],
'desc'=>['ubicacion.ubil_nombre'=>SORT_DESC],
'label'=>'Ubicacion Nombre'
]
]
]);

$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;
}

// grid filtering conditions
$query->andFilterWhere([
'lib_id' => $this->lib_id,
'lib_ubi' => $this->lib_ubi,
'lib_editorial_id' => $this->lib_editorial_id,
]);

$query->andFilterWhere(['like', 'lib_titulo', $this->lib_titulo])
->andFilterWhere(['like', 'lib_autor', $this->lib_autor])
//->andFilterWhere(['like', 'lib_edicion', $this->lib_edicion])
->andFilterWhere(['like', 'lib_isbn', $this->lib_isbn])
->andFilterWhere(['like', 'lib_clasificacion', $this->lib_clasificacion])
->andFilterWhere(['like', 'lib_seccion', $this->lib_seccion])
->andFilterWhere(['like', 'lib_image_src_filename', $this->lib_image_src_filename])
->andFilterWhere(['like', 'lib_image_web_filename', $this->lib_image_web_filename]);

$query->joinWith(['editorial0'=>function($q)//creamos un nuevo filtro
{
$q->where('editorial.edi_nombre LIKE "%' . $this->editorialNombre . '%"');
}]);

$query->joinWith(['libUbi'=>function($q)//creamos un nuevo filtro
{
$q->where('ubicacion.ubil_nombre LIKE "%' . $this->ubicacionNombre . '%"');
}]);

return $dataProvider;
}
}

Как я могу выполнить эту задачу?

0

Решение

[
'attribute' => 'adq_libro_id',
'value' => implode(', ', \yii\helpers\ArrayHelper::map($model->Adqs, 'id',
function ( $model )
{
return $model['adq'];
}
)),
'format' => 'raw'
],

попробуй вот так. Проверьте правильное имя атрибутов

0

Другие решения

В вашей модели Libros.php у вас есть эта функция.

public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}

Это означает, что вы можете получить доступ к отношениям Libros лайк:

// where $model is an instance of Libros
$model->adqs->property_name

Или как функция

$model->getAdqs();
0

По вопросам рекламы [email protected]