Answer the question
In order to leave comments, you need to log in
How to pull data from two tables in yii2?
Hello! There are two related tables production (id, id_category, title, status) and image (id, id_production, imagepath), where each record from production can correspond to several records from image. Next, I try to display pictures from image those that correspond to production with the status status = 1, and the picture should be displayed for each production along with the caption title:
$dataProvider = new ActiveDataProvider([
'query' => Production::find()
->joinWith('image')
->where(['image.id_production' => 'id'])
->where(['status' => 1])
->orderBy('id DESC')->limit(12),
]);
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_workitem',
'summary' => false,
'emptyText' => '',
]);
<?php
use yii\helpers\Html;
?>
<div class="col-xs-12 col-sm-6 col-md-3 isotope-item <?= Html::encode($model->id_category) ?>">
<div class="image-box">
<?php echo Html::a(Html::img("@frontendWebroot/uploads/images/thumbs/$model->imagepath"), "@frontendWebroot/uploads/images/$model->imagepath", ['rel' => 'fancybox', 'title'=>$model->title]); ?>
<div class="overlay-container">
<a class="overlay" src="">
<i class="fa fa-search-plus"></i>
<span><?= Html::encode($model->title) ?></span>
</a>
</div>
</div>
</div>
Answer the question
In order to leave comments, you need to log in
I don’t see the point here for join. We need to make a connection in the production model
public function getImages(){
return $this->hasMany(Images::classname(),['id_production'=>'id']);
}
$dataProvider = new ActiveDataProvider([
'query' => Production::find()
->with('images')
->where(['status' => 1])
->orderBy('id DESC')->limit(12) //обычно лимит задает Pager, но Вам виднее
]);
foreach($model->images as $image){
echo $image->imagepath;
}
//или например взять первый объект из массива объектов
echo $model->images[0]->imagepath;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question