Reputation: 101
I am working with a foreach loop and I want to make some banners in
frontend/layouts/main
I created a model where I have these static functions:
public static function getUrl() {
return Banner::find()->where(['Rel_User' => Yii::$app->user->identity->Id])->all();
}
public static function getImage() {
return Yii::$app->basePath . '/web/' . $this->Image;
}
And I want to display this URL in my main:
<?php foreach (Banner::getUrl() as $key): ?>
<div class="banner">
<a href="<?= $key['Url'] ?>" title="">
<img src="<?=Url::base(true)?>/img/banner.jpg" alt=""></a>
</div>
<?php endforeach; ?>
The problem is that I have 3 banners assigned to the logged user and this loop displays only one banner. What did I do wrong? My second question is, what should I do to display only the URL from my database, because now the URL looks like:
http://my-page.frontend.localhost/www.google.com
but in my database it is:
url= www.google.com
Upvotes: 0
Views: 153
Reputation: 1794
I think your code has serious problem! You have this:
public static function getImage() {
return Yii::$app->basePath . '/web/' . $this->Image;
}
It doesn't any sense of using $this
keyword on a static function. When you made a function as static
, you attach it on class
not on object
and $this
pointer point to an instance
of class
.
For your problem, I suggest define a has-many
relation on your User
model as this:
public function getBanners()
{
return $this->hasMany(Banner::className(), ['Rel_User' => 'id']);
}
and on your main view use something like this code:
<?php foreach (Yii::$app->user->identity->banners as $banner): ?>
<div class="banner">
<!-- Use your Banner model attributes from $banner variable -->
</div>
<?php endforeach; ?>
Upvotes: 1