R
R
RR2015-03-23 15:54:20
Yii
RR, 2015-03-23 15:54:20

Yii2 / hasOne or what am I doing wrong?

Actually, what's wrong?
Model:

namespace common\models;

use Yii;

class Content extends \yii\db\ActiveRecord
{
...
    public function getAuthor() {
        return $this->hasOne(User::className(), ['id' => 'author_id']);
    }
...
}

Controller:
namespace backend\controllers;

use Yii;
use common\models\Content;

class ContentController extends Controller
{
...
    public function actionIndex()
    {
        $data = Content::find()->getAuthor()->all();

        return $this->render('index', [
            'data' => $data,
        ]);
    }
...
}

I am getting an error:
Calling unknown method: yii\db\ActiveQuery::getAuthor()

Kick in the right direction :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
HaruAtari, 2015-03-23
@romkaby

$data = Content::find()->getAuthor()->all();
You have not selected the correct entry.
If you need an author, then you need this:

$data = Content::find()->one()
    ->getAuthor()->one();

If you need all posts together with the authors, then like this:
$data = Content::find()
    ->with('author')
    ->all();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question