我正在尝试从以下查询中获取数据:
SELECT threads.thread_id
, threads.thread_name
, threads.author_id
, users.name
FROM threads
JOIN users
ON threads.author_id = users.id
ORDER
BY thread_id
LIMIT 5
它可以在phpmyadmin中正常工作,但是当我使用Yii2并使用以下代码尝试时:
$query = Threads::find();
$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' => $query->count(),
]);
$threads = $query->select(['threads.thread_id','threads.thread_name','threads.author_id','users.name'])
->from('threads')
->join('INNER JOIN', 'users', 'threads.author_id = users.id')
->orderBy('thread_id')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
然后在访问$ thread-> name的视图中,它给我一个错误,说没有这样的字段,而'threads'表中的每个字段都可以正常工作。
<?php foreach ($threads as $thread): ?>
<li>
<?= var_dump($thread)?>
<a href=" <?= Url::to(['thread/view', 'id' => $thread->thread_id])?>"><?=$thread->thread_name?></a>
<?= Html::encode("{$thread->thread_id} ({$thread->thread_name})") ?>:
<p>Author: <?=$thread->name?></p>
</li>
怎么了?
更新:确切的错误消息
yii\base\ErrorException: Trying to get property of non-object in C:\xampp\htdocs\YiiForum\views\thread\index.php:14
更新:var_dump($ thread)
object(app\models\Threads)#82 (13) { ["thread_id":"app\models\Threads":private]=> NULL ["thread_name":"app\models\Threads":private]=> NULL ["author_id":"app\models\Threads":private]=> NULL ["_attributes":"yii\db\BaseActiveRecord":private]=> array(3) { ["thread_id"]=> string(1) "1" ["thread_name"]=> string(30) "Привет, как дела?" ["author_id"]=> int(1) } ["_oldAttributes":"yii\db\BaseActiveRecord":private]=> array(3) { ["thread_id"]=> string(1) "1" ["thread_name"]=> string(30) "Привет, как дела?" ["author_id"]=> int(1) } ["_related":"yii\db\BaseActiveRecord":private]=> array(0) { } ["_relationsDependencies":"yii\db\BaseActiveRecord":private]=> array(0) { } ["_errors":"yii\base\Model":private]=> NULL ["_validators":"yii\base\Model":private]=> NULL ["_scenario":"yii\base\Model":private]=> string(7) "default" ["_events":"yii\base\Component":private]=> array(0) { } ["_eventWildcards":"yii\base\Component":private]=> array(0) { } ["_behaviors":"yii\base\Component":private]=> array(0) { }
答案 0 :(得分:-2)
可能是有用的
$query = new Query();
$query->select([
'c.id as car_id',
'c.name_ru as car_name',
'c.slug_ru as car_slug',
'cp.price as price',
'cp.sztype_id as sztype_id',
])->from(['c'=>'c_car'])
->leftJoin(['cp'=>'c_car_price'],'cp.car_id=c.id')
->where(['c.collection_id'=>$collections[0]['collection_id'],'cp.show_price'=>self::ACTIVE_ONE])
->limit(6)
->all();