Home > Net >  nested query with laravel model
nested query with laravel model

Time:11-14

I am writing a nested query with Laravel. Namely First, the Truck information is drawn, then I list the data of the vehicle with "truck_history", there is no problem until here, but I want to show the information of the invoice belonging to the "invoice_id" in truck_history. but I couldn't understand how to query, I want to do it in the model, is this possible? If possible, how will it be done?

"ID" COLUMN IN INVOICE TABLE AND "invoice_id" in "InvoiceDetail" match.

enter image description here TruckController

public function getTruck($id)
    {
        $truck = Truck::with(['truckHistory'])->find($id);
        return $truck;
    }

Truck Model

protected $appends = ['company_name'];

    public function companys()
    {
        return $this->belongsTo(Contact::class, 'company_id', 'id');
    }

    public function getCompanyNameAttribute()
    {
       return $this->companys()->first()->name;
    }

    public function truckHistory(){
        return $this->hasMany(InvoiceDetail::class,'plate_no','plate');
    }

CodePudding user response:

So you can add another relationship in the InvoiceDetail::class and add in the truck history. try something like this:

public function truckHistory(){
    return $this->hasMany(InvoiceDetail::class,'plate_no','plate')->with('Invoice');
}

CodePudding user response:

Simply add the following relations (if you don't already have them):

Invoice model :

public function truckHistory()
{
    return $this->hasOne(InvoiceDetail::class);
}

InvoiceDetail model :

public function invoice()
{
    return $this->belongsTo(Invoice::class);
}

And you can get the relation invoice of the relation truckHistory adding a point as separator :

public function getTruck($id)
{
    $truck = Truck::with(['truckHistory.invoice'])->find($id);
    return $truck;
}
  • Related