Giest
Giest

Reputation: 495

Yii2: How to select multiple fields from different tables

My tables

Category
id_category
name

Post
id_post
category_id
title

My query:

Post::find()
->select('post.*, c.name AS catname')
->leftJoin('category c', 'c.id_category = category_id')
->all();

The output just shown the table fields Post, is not the field catname.

Upvotes: 1

Views: 906

Answers (1)

Fabrizio Caldarelli
Fabrizio Caldarelli

Reputation: 3008

1) Define a relation in Post model named 'category', so:

public function getCategory() { 
     return $this->hasOne(Category::className(), ['id_category' => 'category_id']); 
}

2) Then when you query the posts, use 'with' if you need to get category name for each post:

$posts = Post::find()
->with('category')
->all();

3) You can access to category name with:

$post->category->name

Upvotes: 2

Related Questions