模型结合Laravel中的两个表

时间:2017-12-20 22:43:23

标签: php laravel

我有表格" item","付款"," join_payment"。

该项目有import sys from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, QInputDialog, QApplication, QComboBox, QFrame) import numpy as np class GUI(QWidget): def __init__(self): super().__init__() self.initgui() def initgui(self): # # Set up GUI # self.setGeometry(100, 100, 400, 400) self.move(300, 300) combobox = QComboBox(self) for i in range(1, 10, 1): combobox.addItem(str(i + 1)) combobox.activated[str].connect(self.comboboxchanged) self.setWindowTitle("Testing Easy Setup") self.show() def comboboxchanged(self, text): frame = QWidget(self) frame.hide() for num in range(0, int(text), 1): QLineEdit(frame).move(60, num * 19) frame.show() if __name__ == '__main__': app = QApplication(sys.argv) gui = GUI() sys.exit(app.exec_()) ,付款方式为@Component( selector: 'box-component', templateUrl: 'box_component.html', directives: const[CORE_DIRECTIVES, BoxComponent] ) class BoxComponent 。 join_payment包含行idid

付款可能包含许多项目,这些项目将在join_payment表中注册。

我想用这些项目创建日志,我目前正在控制器中执行此操作:

item_id

有没有办法在模型中推出这个?

2 个答案:

答案 0 :(得分:3)

我建议使用Eloquent关系。 https://laravel.com/docs/5.5/eloquent-relationships#many-to-many。如果您致电联接表item_payment,则会更加轻松:

class Item extends Model {
    public function payments(){
        return $this->belongsToMany(Payments::class)
    }
}

class Payment extends Model {
    public function items(){
        return $this->belongsToMany(Item::class)
    }
}

class ItemPayment extends Model {
    public function item(){
        return $this->belongsTo(Item::class)
    }
    public function payment(){
        return $this->belongsTo(Payment::class)
    }
}

然后,您可以通过多种方式访问​​所需的数据:

$items = Item::all();
foreach($items as $item){
    $item->payments; //returns all payments belonging to this item
}


$payments = Payment::all();
foreach($payments as $payment){
    $payment->items; //returns all items belonging to this payment
}


$itemPayments = ItemPayment::all();
foreach($itemPayments as $itemPayment){
    $itemPayment->item; //the item for this join
    $itemPayment->payment; //the payment for this join
}

很抱歉更改了您的班级和牌桌名称,但这些约定会让您在Laravel中的生活更轻松

答案 1 :(得分:1)

您的项目模型中的

使用此

public function payment()
{
   return $this->hasOne('App\Payment','join_payment','payment_id','item_id');
}

然后在你循环检查

foreach($items as $item){
   dd($item->payment);
}