【问题标题】:BDD request with inner join with Yii与 Yii 进行内部连接的 BDD 请求
【发布时间】:2015-08-11 15:53:59
【问题描述】:

我是 Yii 框架的新手。 我的目标是显示当前用户拥有的所有“平板电脑”。

在我的模型中,我有 2 个表,Tablette 和 Client。在 Tablette 中,有一个外键指向 Client 表,用于标识 Tablette 的所有者。

这是我的控制器代码:

public function displayTablettesUser()
{
    $user_id = Yii::$app->user->getId();

    $var_tablette = Tablette::find()->where(['ID_fk_client' => 'user_id']);

    // Send toutes les tablettes du client
    return $this->render('profile', array('tablettes' => $var_tablette));
}

这是我的 php 代码,用于显示当前用户的平板电脑:

<?php

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;

AppAsset::register ( $this );

foreach($tablettes as $tablette){
        echo($tablette->code)." : ".$tablette->iDFkClient->firstName."</br>";
}


?>

当我加载我的网页时,我收到了这个错误:

试图获取非对象的属性。

我假设我是这个框架的初学者,我可能错过了一些东西,但我不知道是什么。

【问题讨论】:

  • 尝试做 Tablette::find()->where(['ID_fk_client' => 'user_id'])->all();
  • 我不再收到错误消息,但没有显示任何内容! (用户 ID 为 1,我的平板电脑指向客户端 ID 1)我真的不明白为什么它不起作用:(!
  • where(['ID_fk_client' => 'user_id']); - 将其更改为 where(['ID_fk_client' => $user_id]);我想你很高兴
  • 我也没有得到任何东西:/

标签: php mysql yii yii2


【解决方案1】:

除了 cmets 之外,如果你已经用 Gii 生成了模型,你应该在 Tablette 模型中有一个函数,比如:

public function getClient()
{
    return $this->hasOne(Client::className(), ['id' => 'ID_fk_client']);
}

所以观点:

foreach($tablettes as $tablette){
        echo ($tablette->code)." : ".$tablette->getClient()->one()->firstName."</br>";
}

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2022-08-05
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2013-11-19
    • 2014-05-31
    • 2012-11-04
    • 1970-01-01
    相关资源
    最近更新 更多