Skip to content
Advertisement

relations with 4 tables in laravel

I have four tables as follows.

Services_cats Session_pat Invoice_item Invoice
id id id id
name services_cat_id service_id code
patient_id invoice_id discount

I need to have relations among them with one Eloquent query in Laravel. Below is what I have reached so far; I used many-to-many relations in the invoice table.

public function invoice_item()
{
    return $this->belongsToMany(Session_pat::class, 'invoice_items', "invoice_id", 
    "service_id", "id", "id");
}

And I used this code to access the four tables.

$status4 = Invoice::select('id')->with(['invoice_item' => function ($q){
    $q->select('id', 'services_cat_id')
        ->with(['service_cat' => function ($q) {$q->select('id as myid', 'name');}])
            ;}])
            ->where('id', 122)->get();

but I get this error

SQLSTATE[23000]: Integrity constraint violation: 1052 Column ‘id’ in field list is ambiguous (SQL: select id, services_cat_id, invoice_items.invoice_id as pivot_invoice_id, invoice_items.service_id as pivot_service_id from session_pats inner join invoice_items on session_pats.id = invoice_items.service_id where invoice_items.invoice_id in (122) order by id desc)

Advertisement

Answer

You Should Specific The Table Name, WHen Using Same Column Name In Query.

Rule: tableName.column EX: invoiceTable.id

$status4 = Invoice::select('TableName.id')->with(['invoice_item' => function ($q){
            $q->select('TableName.id', 'services_cat_id')
                ->with(['service_cat' => function ($q) {$q->select('TableName.id as myid', 'name');}])
                ;}])
            ->where('TableName.id', 122)->get();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement