1

I'm trying to implement a simple select method into a eloquent with. So, I have this code that works correctly.

$usersInfo = User::with(['product' => function($query) use($request) {
    $query->whereBetween('date', [$request->get('datefrom'), $request->get('dateto')]);
}])->get();

But if I put a select into the query function, the query stop working and return an empty value into the product array.

$usersInfo = User::with(['product' => function($query) use($request) {
    $query->select(['date', 'name'])
        ->whereBetween('date', [$request->get('datefrom'), $request->get('dateto')]);
}])->get();

I know that if use DB::table() is possible to do this stuff.

So, my question is. If there any possibility to put this select into the with, in Eloquent?

Thanks

mbozwood
  • 1,383
  • 12
  • 23
dieroste
  • 394
  • 1
  • 3
  • 15

3 Answers3

3

You need to pass the primary key of the other model into the select to retrieve the necessary results. Without seeing the product relation function I cannot accurately determine what should be done, however it will probably be id.

$query->select('id', 'date', 'name')...

Referenced here

mbozwood
  • 1,383
  • 12
  • 23
0

you can try this, works with 5.8 version

$usersInfo = User::with('product')
        ->whereBetween('date', [$request->get('datefrom'), $request->get('dateto')]);
}])->get();

$userInfo = $userInfo->map(function($data){
   return collect([

    ...................
    ...........
    'product' => $data->product->map(function($productData){
            'date' => productData->date,
            'name' => productData->name
        })
    ])

})
ANIK ISLAM SHOJIB
  • 3,002
  • 1
  • 27
  • 36
0

To Select Only Particular columns from table just pass as the below code

$data   =   Post::all('id', 'title','content');