Yii2 使用 ActiveRecord 实现三个表之间的关系

问题描述 投票:0回答:1

我的mysql数据库中有三个表,如下图所示:Relation

现在,使用 gii,我创建了这样的模型:

用于 BuktiPenerimaan 餐桌

class BuktiPenerimaan extends \yii\db\ActiveRecord{
/**
 * @return \yii\db\ActiveQuery
 */
public function getInvoiceReports()
{
    return $this->hasMany(InvoiceReport::className(), ['bukti_penerimaan_id' => 'id']);
}
}

和发票报告:

class InvoiceReport extends \yii\db\ActiveRecord{

/**
 * @return \yii\db\ActiveQuery
 */
public function getInvoiceReportDetails()
{
    return $this->hasMany(InvoiceReportDetail::className(), ['invoice_id' => 'id']);
}

我的问题是,如果我创建了一个来自 BuktiPenerimaan 的对象,如何访问表中的所有记录

invoice_report_detail

我这样使用:

$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice  = $model->invoiceReports; //exist
$dataInvoiceDetail = $model->invoiceReports->invoiceReportDetails // failed, always null.

请多多指教

php mysql activerecord yii2
1个回答
0
投票

$dataInvoice  = $model->invoiceReports;
InvoiceReport
对象的数组。

您需要循环每个

InvoiceReport
才能获得相关的
InvoiceReportDetail

$model = $this->findModel($id); // model Bukti Penerimaan.
$dataInvoice  = $model->invoiceReports; //exist , but array of objects
$dataInvoiceDetail = [];
foreach($dataInvoice as $dInvoice):
   $dataInvoiceDetail[] = array_merge($dataInvoiceDetail,$dInvoice->invoiceReportDetails );
endforeach;
// $dataInvoiceDetail contains all invoice_report_detail 
© www.soinside.com 2019 - 2024. All rights reserved.