[英]How to get Data from INNER JOIN request in Yii2?
I am trying to get data from this query: 我正在尝试从此查询获取数据:
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
It works in phpmyadmin just fine, but when i try it with Yii2 with the code below: 它可以在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();
And then in the view accessing $thread->name, it gives me an error, saying there's no such field, while every field from 'threads' table works fine. 然后在访问$ 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>
What is wrong? 怎么了?
UPDATE: Exact Error message 更新:确切的错误信息
yii\base\ErrorException: Trying to get property of non-object in C:\xampp\htdocs\YiiForum\views\thread\index.php:14
UPDATE: var_dump($thread) 更新: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) { }
may be its can useful 可能是有用的
$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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.