我是Laravel的初学者,我需要在laravel刀片中显示名称而不是ID。
这些是数据库中的表:
Table city
+----+--------+
| id | name |
+----+--------+
| 1 | Vienna |
| 2 | Linz |
+----+--------+
Table zip
+----+---------+------+-------------+
| id | city_id | code | name |
+----+---------+------+-------------+
| 1 | 1 | 1010 | 1. district |
| 2 | 1 | 1020 | 2. district |
| 3 | 1 | 1030 | 3. district |
| 4 | 2 | 4020 | Linz |
+----+---------+------+-------------+
Table street
+----+--------+---------------+
| id | zip_id | name |
+----+--------+---------------+
| 1 | 1 | Burgring |
| 2 | 1 | Seilergasse |
| 3 | 2 | Praterstrasse |
+----+--------+---------------+
Table orders
+----+---------+------+-----+--------+
| id | orderno | city | zip | street |
+----+---------+------+-----+--------+
| 1 | 100001 | 1 | 2 | 3 |
| 2 | 100002 | 1 | 1 | 2 |
| 3 | 100003 | 1 | 1 | 1 |
+----+---------+------+-----+--------+
控制器
$orders = Order::all();
return view('orders-show', compact('orders'));
刀片
@foreach($orders as $order)
<tr>
<td>{{$order->id}}</td>
<td>{{$order->orderno}}</td>
<td>{{$order->city}}</td>
<td>{{$order->zip}}</td>
<td>{{$order->street}}</td>
</tr>
@endforeach
我相信有比为每个项目创建视图功能更好的方法。在阅读时,我想通过Model可以连接城市,邮政编码和街道,例如belongsTo和hasMany-也许我错了...
有人可以帮助我吗?谢谢
您可以使用One To Many关系来完成。
首先,更新您的orders
表以正确使用Eloquent Relationships:
+----+---------+---------+--------+-----------+
| id | orderno | city_id | zip_id | street_id |
+----+---------+---------+--------+-----------+
| 1 | 100001 | 1 | 2 | 3 |
| 2 | 100002 | 1 | 1 | 2 |
| 3 | 100003 | 1 | 1 | 1 |
+----+---------+---------+--------+-----------+
1。定义city
和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
表之间的关系:
将此添加到street
表迁移中:
$table->foreign('zip_id')->references('id')->on('zip')->onDelete('cascade');
然后,在zip()
模型类中定义Street
方法:
public function zip()
{
return $this->belongsTo('App\Zip');
}
3。定义city
,zip
,street
和orders
表之间的关系:
将这些行添加到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中,表名默认为复数。如果要使表名保持单数,请不要忘记在模型内部设置$table
属性。例如,在您的City
模型类中:
protected $table = 'city';