简体   繁体   中英

How to combine three SQL tables in Laravel?

I have 3 tables - Collections, Shipments, and Parcels.

Question 1

A collection has one to many shipments. A shipment may have one to many parcels per shipments.

Collections table
id
user_id

Shipments table
id
collections_id
shipment information(currently irrelevant)

Parcels table
id
shipment_id
parcelnumber

Show.blade

How can I display them in my blade view as follows?

Blade view

Question 2

Create.blade

When a user adds a new Shipment, a collection should be created and the newly created shipment should be linked with the collection. How could I assign the newly created shipment to the collection?

I truly need advice on whether I should start over and change the database tables build

If any additional information is needed regarding to Models/Views/Controllers please let me know.

Collections Model

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


}

Kind regards,

user3088327

Try This Solution in Your Model

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

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

In blade

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

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

Use another method with:("use 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();

Or: In model(shipments):

public function Shipments() {
    return $this->belongsTo('App\collections'); //can add ->select(..)
}

public function Parcels() {
    return $this->hasMany('App\Parcels');
}

In controller:

$collections= Shipments::with('shipments')->with('parcels')->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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