1

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.

2
  • Show the code related to the query and the output please Commented Jan 4, 2016 at 22:02
  • "Getting unknown property: app\models\Post::catname" I have "$posts = Post::find()..." and error is at line: "foreach ($posts as $post) { $post->catname; } Commented Jan 4, 2016 at 22:10

1 Answer 1

2

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
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.