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 关注
- 124 浏览
添加回答
举报