Laravel 5.5 can't get selected column data using belongsTo
Laravel 5.5 can't get selected column data using belongsTo
I have 2 models (User & UsersDetails) in relation with Eloquent Laravel.
User
UsersDetails
Model "User" Realation With 'SelDetails'
public function SelDetails
return $this->belongsTo('AppUsersDetails', 'users_id');
I want to get only two column 'created_by_id', 'created_by_name' from SelDetails
UserController
$users = User::with(['SelDetails' => function($query)
$query->select(['created_by_id', 'created_by_name']);
])
->where('is_active', '=', 0)
->orderBy('id', 'desc')
->get();
I am getting data from User but getting blank in SelDetails
User
SelDetails
[relations:protected] => Array
(
[SelDetails] =>
)
Please correct me.
$query->select(['user_id', 'created_by_id', 'created_by_name']);
add created_by_id in relation :
public function SelDetails return $this->belongsTo('AppUsersDetails', 'users_id', 'created_by_id'); – Mohammad
Sep 17 '18 at 7:39
public function SelDetails return $this->belongsTo('AppUsersDetails', 'users_id', 'created_by_id');
@Mohammad that's not working
– Ram Chander
Sep 17 '18 at 15:00
3 Answers
3
guys thanks for your precious response on this issue. i got the solution via following way.
changes in "User" model Relation With 'SelDetails'
public function SelDetails
#return $this->belongsTo('AppUsersDetails', 'users_id');// the old one
return $this->hasOne('AppUsersDetails', 'users_id');
changes in "UserController"
$users = User::with('SelDetails')->where('is_active', '=', 0)->orderBy('id', 'desc')->get();
that's the changes that I have made and got the result

Thanks
I might be wrong but it might be the array in select, try
$query->select('created_by_id', 'created_by_name');
i already tried that way but not working
– Ram Chander
Sep 17 '18 at 15:02
Thanks for your response
– Ram Chander
Sep 17 '18 at 15:21
Have you tried something like
$users = AppBook::with('author:id,name')->get(); from the documentation?
In your case it should looks like:
$users = AppBook::with('author:id,name')->get();
User::with('SelDetails:created_by_id,created_by_name')
->where('is_active', '=', 0)
->orderBy('id', 'desc')
->get();
with() method can take string (or array filled by strings) eg. relationName:column1,column2.
with()
relationName:column1,column2
This is the answer. The documentation even describes exactly how to do this.
– Don't Panic
Sep 17 '18 at 4:08
it's not working for me. thanks for your response. BTW I just found the solution.
– Ram Chander
Sep 17 '18 at 15:23
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
add column user_id in select :
$query->select(['user_id', 'created_by_id', 'created_by_name']);– Mohammad
Sep 17 '18 at 7:35