Hi,
I need some help for my yii2 project.
I have two tables connected via a junction table:
[b][u]
Table 1: virtual_printers (id, name)[/u][/b]
public function getVirtualPrinterMappings()
{
return $this->hasMany(VirtualPrinterMapping::className(), ['virtual_printer_id' => 'id']);
}
public function getPrinters()
{
return $this->hasMany(Printers::className(), ['id' => 'printer_id'])
->via('virtualPrinterMappings');
}
Table 2: printers (id, ip, name)
public function getVirtualPrinterMappings()
{
return $this->hasMany(VirtualPrinterMapping::className(), ['printer_id' => 'id']);
}
public function getVirtualPrinters()
{
return $this->hasMany(VirtualPrinters::className(), ['id' => 'virtual_printer_id'])
->via('virtualPrinterMappings');
}
Junction table: virtual_printer_mappings (virtual_printer_id, printer_id, row)
public function getPrinter()
{
return $this->hasOne(Printers::className(), ['id' => 'printer_id']);
}
public function getVirtualPrinter()
{
return $this->hasOne(VirtualPrinters::className(), ['id' => 'virtual_printer_id']);
}
I now want to get the name of the real printer stored in the printers table with the ID of the virtual printer and the row.
I tried this:
$virtual_printer = VirtualPrinters::find()
->with(['virtualPrinterMappings' => function ($query) use (&$row) {
$query->select(['printer_id']);
$query->andWhere(['row' => $row]);},])
->where(["id" => $item->virtual_printer_id])
->One();
I can see on the yii debugger that the sql seems good:
SELECT "printer_id" FROM "virtual_printer_mapping" WHERE ("row"='B') AND ("virtual_printer_id"=3)
Result should be ONE printer. Now I want to acess the data like this: $virtual_printer->printer->name; But it is not working.
I think there should be a smarter solution?