0

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
2
  • 1
    For the question of the links not being external, you need to put http:// before <?= $key['Url'] ?> Commented Mar 9, 2016 at 16:33
  • Why you repeat 3 time the same code in foreach ? and why in the firts there is not div ? Commented Mar 9, 2016 at 18:52

1 Answer 1

1

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; ?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.