繁体   English   中英

如何在Laravel中合并三个SQL表?

[英]How to combine three SQL tables in Laravel?

我有3张桌子-托收,托运和包裹。

问题1

一个集合有一对多的发货。 每批货物可能有一个到多个包裹。

Collections table
id
user_id

Shipments table
id
collections_id
shipment information(currently irrelevant)

Parcels table
id
shipment_id
parcelnumber

Show.blade

如何在刀片视图中如下显示它们?

刀片视图

问题2

Create.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');
}


}

亲切的问候,

user3088327

在您的模型中尝试此解决方案

public function Shipments() {
    return $this->hasOne(App\Model\Shipments:class);
}

public function Parcels() {
    return $this->hasManyThrough(App\Model\Parcels:class,App\Model\Shipments:class);
}

刀片式

$comments = App\Model\Collection::find(1)->Shipments()->Parcels()->get();

foreach ($Shipments as $Shipment) {
    //
}
foreach ($Parcels as $Parcel) {
    //
}

使用另一种方法:(“使用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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM