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
aspivot_invoice_id
,invoice_items
.service_id
aspivot_service_id
fromsession_pats
inner joininvoice_items
onsession_pats
.id
=invoice_items
.service_id
whereinvoice_items
.invoice_id
in (122) order byid
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();