Home > Enterprise >  Laravel Eloquent with query
Laravel Eloquent with query

Time:10-14

I want to pull the invoice detail with the "id" number of 3 in the tools table from the "invoice_details" table. "plate" "invoice_details" relationship "plate_no" in the "trucks" table, but when I pull the data, a different data is coming, where am I making a mistake?

public function getTruck($id)
    {
        $truck = Truck::find($id)->with(['truckHistory'])->first();
        return $truck;
    }
Truck extends Model
public function truckHistory(){
        return $this->hasMany(InvoiceDetail::class,'plate_no','plate');
    }

Normally the incoming data is TRUE when I don't write a with condition THIS IS TRUE

$truck = Truck::find(3);
{
    "id": 3,
    "plate": "73AD323",
    "created_at": "2021-10-13T08:38:23.000000Z",
    "updated_at": "2021-10-13T08:38:23.000000Z"
}

When I type a condition, the id is wrong.

 $truck = Truck::find(3)->with(['truckHistory'])->first(); 
{
    "id": 1,
    "plate": "33EER36",
    "created_at": "2021-10-11T06:01:29.000000Z",
    "updated_at": "2021-10-11T06:01:29.000000Z",
    "truck_history": [
        {
            "id": 1,
            "plate_no": "33EER36",
            "created_at": "2021-10-11T06:03:16.000000Z",
            "updated_at": "2021-10-11T06:03:16.000000Z"
        },
        {
            "id": 2,
            "plate_no": "33EER36",
            "created_at": "2021-10-11T06:06:18.000000Z",
            "updated_at": "2021-10-11T06:06:18.000000Z"
        }
    ]
}

CodePudding user response:

Using first will return the first record of the trucks table, to do so you can use

Truck::with(['truckHistory'])->find($id);
  • Related