discoverAnkit
discoverAnkit

Reputation: 1151

Join Query using ActiveRecord in Yii 2.0 Framework

I am struggling big time with ActiveRecord.

$coupons = Coupon::find()
                     ->select(['{{coupon}}.*','({{website}}.`websitename`) AS WebsiteName'])
                     ->leftjoin('website', '`coupon`.`websiteid`=`website`.`websiteid`')
                     ->limit(10)
                     ->all();

This is the join query but its only populates the properties/attributes of the class "Coupon" which seems to be by the books. How do I access a column from the other table "Website"?

<?php foreach ($coupons as $coupon): ?>
            <li>
                <?= $coupon->WebsiteName?><br>
            </li>
<?php endforeach; ?>

This one throws an "unknownPropertyType" exception.

Upvotes: 2

Views: 95

Answers (2)

Tony
Tony

Reputation: 5867

Add public property into your Coupon class public $WebsiteName;

As another option you can access your WebsiteName by defining a relation in your Coupon model:

public function getWebsite()
{
    $this->hasOne(Website::classname(), ['websiteid' => 'websiteid']);
}

And then change your query:

$coupons = Coupon::find()->with('website')->limit(10)->all();

Then to access property:

<?php foreach ($coupons as $coupon): ?>
    <li>
        <?= $coupon->website->WebsiteName?><br>
    </li>
<?php endforeach; ?>

Upvotes: 4

Makarenko_I_V
Makarenko_I_V

Reputation: 111

Use print_r($coupon) to see structire of your`s model. To get name, you must must call something like: $coupon->website->Name

But I recomend you use links hasOne / hasMany. Read detail here.

Upvotes: 0

Related Questions