1 回答

TA貢獻1802條經驗 獲得超6個贊
您可以使用一對多關系來執行此操作。
首先,更新您的表格以正確使用雄辯關系:orders
+----+---------+---------+--------+-----------+
| id | orderno | city_id | zip_id | street_id |
+----+---------+---------+--------+-----------+
| 1 | 100001 | 1 | 2 | 3 |
| 2 | 100002 | 1 | 1 | 2 |
| 3 | 100003 | 1 | 1 | 1 |
+----+---------+---------+--------+-----------+
1. 定義城市和 zip 表之間的關系:
將其添加到表遷移中:zip
$table->foreign('city_id')->references('id')->on('city')->onDelete('cascade');
然后,在模型類中定義方法:city()Zip
public function city()
{
return $this->belongsTo('App\City');
}
2. 定義 zip 和街道表之間的關系:
將其添加到表遷移中:street
$table->foreign('zip_id')->references('id')->on('zip')->onDelete('cascade');
然后,在模型類中定義方法:zip()Street
public function zip()
{
return $this->belongsTo('App\Zip');
}
3. 定義城市、郵政編碼、街道和訂單表之間的關系:
將以下行添加到表遷移中:orders
$table->foreign('city_id')->references('id')->on('city');
$table->foreign('zip_id')->references('id')->on('zip');
$table->foreign('street_id')->references('id')->on('street');
然后,為模型類中的每個關系定義一個方法:Order
public function city()
{
return $this->belongsTo('App\City');
}
public function zip()
{
return $this->belongsTo('App\Zip');
}
public function street()
{
return $this->belongsTo('App\Street');
}
4. 現在在視圖(邊欄選項卡)中使用它們:
@foreach($orders as $order)
<tr>
<td>{{ $order->id }}</td>
<td>{{ $order->orderno }}</td>
<td>{{ $order->city['name'] }}</td>
<td>{{ $order->zip['code'] }}</td>
<td>{{ $order->street['name'] }}</td>
</tr>
@endforeach
注意:默認情況下,表名在Laravel Eloquent中是復數形式。如果要使表名保持單數,請不要忘記在模型中設置該屬性。例如,在模型類中:$tableCity
protected $table = 'city';
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報