简体   繁体   中英

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.

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; ?>

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM