获得联合表的价值Yii 2

时间:2016-09-02 04:24:05

标签: php mysql join yii2

您好我正在尝试从连接表schead.section访问一个值来存储在subjectcontainer.section中,主要是我使用的是scstock数据,但是部分部分位于schead.section中,所以我做的是加入schead和schstock一起使我可以访问section列。这就是我所做的。

     $subject = ActiveCurriculum::find()
          ->select('scstock.*')
          ->leftJoin('schead', 'schead.TrNo = scstock.TrNo')
          ->where([ 'schead.TrNo' => $TrNo])
          ->one();

    $activesubject = new ActiveSubject();
    $activesubject->clientid = $clientid;
    $activesubject->TrNo = $subject->TrNo;
    $activesubject->subjectcode = $subject->subjectcode;
    $activesubject->schedday = $subject->schedday;
    $activesubject->schedtime = $subject->schedtime;
    $activesubject->section = $subject->section;
    $activesubject->room = $subject->room;
    $activesubject->units = $subject->units;
    $activesubject->save();
//reduces the slot of ccsubject by 1
     $subject->slots = $subject->slots - 1;
     //never forget the saving part
     $subject->save();

首先$subject将访问sctock表以通过TrNo加入schead。然后$activesubject将访问subjectcontainer表以存储值。现在我的问题是我收到此错误。

enter image description here

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

确保定义模型中Schead对象的关系。这种关系的例子:

/**
 * @property $schead Schead
 */
class YourModel extends \yii\db\ActiveRecord
{
    /**
     * @return Schead
     */
    public function getSchead()
    {
        return $this->hasOne(Schead::className(), ['field1' => 'field2']);
    }
}

此外,$subject->schead.section是访问相关模型属性的错误方法。请改用$subject->schead->section。如果schead是可选的,请不要忘记首先检查相关对象的存在,例如:

$subject->schead ? $subject->schead->section : null

同时检查拼写错误的代码(可能是sched / schead?)。您可以在official docs中了解有关处理关系的更多信息。