sql - 如何在 Laravel 中合并三个 SQL 表?
问题描述
我有 3 张表 - Collections、Shipments 和 Parcels。
问题 1
一个集合有一对多的发货。每批货件可能有一个到多个包裹。
Collections table
id
user_id
Shipments table
id
collections_id
shipment information(currently irrelevant)
Parcels table
id
shipment_id
parcelnumber
Show.blade
如何在我的刀片视图中显示它们,如下所示?
问题2
创建.blade
当用户添加新货件时,应创建一个集合,并且新创建的货件应与该集合链接。如何将新创建的货件分配给集合?
我真的需要关于是否应该重新开始并更改数据库表构建的建议
如果需要有关模型/视图/控制器的任何其他信息,请告诉我。
集合模型
namespace App;
use Illuminate\Database\Eloquent\Model;
class Collections extends Model
{
public function Shipments() {
return $this->hasMany('App\Shipments');
}
public function Parcels() {
return $this->hasManyThrough('App\Parcels','App\Shipments');
}
}
亲切的问候,
用户3088327
解决方案
使用另一种方法:("使用 Illuminate\Support\Facades\DB;")
$combine = DB::table('collections')
->JOIN('shipments','collections.id,'=',shipments.collection_id')
->JOIN('parcels','parcels.shipments_id','=','shipments.id')
->SelectRaw('combines.id as chipID, ...')
->get();
或:在模型(出货量)中:
public function Shipments() {
return $this->belongsTo('App\collections'); //can add ->select(..)
}
public function Parcels() {
return $this->hasMany('App\Parcels');
}
在控制器中:
$collections= Shipments::with('shipments')->with('parcels')->get();