Reputation: 1092
Table A
id---- B_id------ C_id
1------ 1------------1
2-------2------------2
Table B
id---name-----------D_ID
1----merchant1-----1
2----merchant2------2
Table C
id--reason
1---reason1
2---reason2
Table D
id--market
1 market1
2 market2
I want the result like this.
[{
id=>1,
B_ID =>1,
B_name=>merchant1,
D_ID=>1,
market=>market1,
C_id=>1,
reason=>reason1},{
id=>2,
B_ID =>2,
B_name=>merchant2,
D_ID=>2,
market=>market2,
C_id=>2,
reason=>reason2}]
I got this answer from direct queries. I want to know is it possible using laravel relations and models? If yes could you please tell how?
Upvotes: 0
Views: 47
Reputation: 848
Yes you can query for model A and eager load the rest of the models:
$modelA->with(['modelB.modelD', 'modelC'])->get();
For it to work you need a relationship on model A for modelB and modelC, and a relationship on modelB for modelD.
UPDATE
You can map over the results, for example like this:
$modelACollection->map(function($modelA) {
return [ "id" => $modelA->id,
"B_ID" => $modelA->modelB->id,
"B_name => $modelA->modelB->name,
"D_id" => $modelA->modelB->modelD->id,
"market" => $modelA->modelB->modelD->market,
"C_id" => $modelA->modelC->id,
"reason" => $modelA->modelC->reason
]
Upvotes: 1