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

时间:2018-09-27 08:07:43

标签: sql 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

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

Blade view

问题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

2 个答案:

答案 0 :(得分:0)

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

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) {
    //
}

答案 1 :(得分:0)

使用另一种方法:(“使用Illuminate \ Support \ Facades \ DB;”)

void display() const
{
    if (!top) {
        std::cout << "Stack is empty!\n";
        return;
    }

    for(node *current = top; current; current = current->next)
        cout << current->data << ' ';
}

或: 在型号(出货)中:

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