如何在连接表中设置java 's Eloquent关系


How to setup Laravel's Eloquent relationship in joining tables?

我很困惑如何设置Laravel的Eloquent关系,以便从其他表中显示信息。

我有3个表:

1. tblbill

 fields: id, title, total.

2. tblbillcontent

 fields: id, BillId, ItemId, qty, price

3. tbliteminfo

fields: id, itemName

我想在我的表上显示以下数据。观点:

id|  itemName | qty | price | total | bill Id
 1   itemNo1     33    10     330       1
 2   itemNo2     20    11     220       1 

到目前为止,我只是使用正常的Eloquent查询:

 $id = 1;
 $items = BillContent::where('billId','=',$id)->get();
结果:

id|  itemName | qty | price | total | bill Id
 1    2(itemID)  33    10     330       1
 2    3(itemID)  20    11     220       1 

我如何将itemID替换为itemName,这将从tblItemInfo字段获得?我将如何设置和运行查询?如果我只使用普通的查询生成器,我就可以得到预期的结果。但我想知道如何能够做到这一点,使用雄辩。

实际上这很简单,你必须告诉Eloquent如何设置关系。在您的模型中(您有模型,对吗?)像这样相互添加相关的列;

// Bills
public function rows() {
    return $this->hasMany('BillContents', 'bill_id');
}
// Items
public function bills() {
    return $this->hasMany('BillContents', 'item_id');
}
// BillContent
public function item() {
    return $this->belongsTo('Items', 'item_id');
}
public function bill() {
    return $this->belongsTo('Bills', 'bill_id');
}

当您查询关系时,假设您想转储账单的内容;

// Controller Side
$bill = Bills::find($id);
// Blade Template Side
@foreach ($bill->rows as $row) // See how we used ->items here?
    <tr>
        <td>{{$row->item->name}}</td> <!-- See how we used $row->item here? -->
    </tr>
@endforeach

假设我们正在查看一个项目,我们想知道我们在哪些账单中使用了它;

// Controller Side
$item = Items::find($id);
// Blade Template Side
@foreach ($item->bills as $bill) // See how we used ->bills here?
    <tr>
        <td>{{$bill->id}}</td> <!-- See how we used $bill here? -->
    </tr>
@endforeach

我可以创建更多的例子,但这个主题在Laravel文档中有深入的解释,我认为你应该再看一遍。