Yehia Awad
Yehia Awad

Reputation: 2978

Yii2 access the Joined table column

I am new to Yii2 and I am wondering how to access the values of a relational table in ActiveRecord

for Instance we have these 2 Models:

Supplier Has Many Product

Product Has One Supplier

class Supplier extends ActiveRecord{

        public function getProducts(){
            return $this->hasMany(Product::className(),["supplier_id"=>"id"]);
        }
        public static function tableName(){
            return 'supplier';
        }
    }

class Product extends ActiveRecord
{
    public function getSupplier(){
        return $this->hasOne(Supplier::className(),['id'=>'supplier_id']);
    }
    public static function tableName()
    {
        return 'product';
    }
}

To Access the Product data I use this line of code

$product=Product::find()->joinWith('supplier')->all();
var_dump($product);

This Code gives me Correctly the data of Product table but I can't access the Supplier data value, why ? How to Access the value of joined Table ?

Upvotes: 0

Views: 1661

Answers (2)

Dani
Dani

Reputation: 925

If you want to access the supplier data through joinWith use the following

$product=Product::find()->joinWith('supplier')->all();

it will return array if you want to access the supplier data then use the following

$product[0]->supplier

it will return the supplier modal, you can now access any attribute like

$product[0]->supplier->name

Upvotes: 0

user3164240
user3164240

Reputation:

If you want to access join data then use asArray():

Product::find()->joinWith("supplier")->asArray()->all();

Upvotes: 2

Related Questions