PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, February 16, 2022

[FIXED] Laravel Eloquent get relation field

 February 16, 2022     eloquent, laravel, laravel-5.5, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing