Issue
I have a need to get a field from the relation from within the eloquent object.
I am using datatables to pass the eloquent object across for viewing.
I have an Model called Offices and a Model called Regions
Offices id name region -> belongsto regions
Regions id name
I need to get something like this: Offices.id, Offices.name, Regions.name
I have tried the below but that fails, how would I get the regions name in the get method?
$ReportData = Offices::with('region')->get(['id', 'name', 'region.name']);
return datatables()->eloquent($ReportData)
Solution
To limit your query results to specific columns, and include that of a relationship, you can use ->join()
, coupled with ->select()
:
$reportData = Offices::join("regions", "offices.region_id", "=", "regions.id")
->select("offices.id", "offices.name", "regions.name AS region_name")
->get();
Note: Had to guess on the join
logic; could be inverse (regions.office_id
, etc)
Then, when accessing the contents of $reportData
, you will only have access to three columns:
foreach($reportData AS $data){
$data->id;
$data->name;
$data->region_name;
}
Answered By - Tim Lewis
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.