I'm new to Lumen and trying to make a simple REST API app. I want one of the endpoints to be able to display all records from a "storeItems" table but add a field to each record with its' categories and paginate them.
So at the moment I have the usual
$products = DB::table('storeItems as i')
->where('i.B2BAvailable', '=', '1')
->select('i.title','i.EAN','i.vendor','i.productType','i.ID as productID','i.releaseDate',DB::raw('(CASE WHEN (i.releaseDate > NOW()) THEN 1 ELSE 0 END) AS announced'))
->orderBy('i.releaseDate', 'desc')
->paginate(100);
return response()->json($products);
This gives out the expected result, but if I want to iterate over the results and add a field from a different table...like this:
foreach($products as $product) {
$genres = DB::table('sCategoryConnector as ggc')
->join('sCatGenre as gg','gg.ID','=','ggc.ID_sCatGenre')
->where('ggc.EAN', '=', DB::raw("'".$product->EAN."'"))
->select('gg.tag')
->orderBy('gg.ID', 'asc')
->get();
if (count($genres) > 0) {
$i=0;
foreach($genres as $genre) {
//$product['genres'][$i] = $genre['tag'];
$propName = 'genre'.$i;
$product->genres->$propName = $genre->tag;
$i ;
}
}
}
But Lumen is outputting: Creating default object from empty value error and marking this line:
$product->genres->$propName = $genre->tag;
What am I doing wrong? Thanks up front.
CodePudding user response:
So I was rushing a bit...should have replaced assigning genres like this:
if (count($genres) > 0) {
$i=0;
$product->genres = $genres;
/*
foreach($genres as $genre) {
//$product['genres'][$i] = $genre['tag'];
$propName = 'genre'.$i;
$product->genres->$propName = $genre->tag;
$i ;
}
*/
}
So the correct way to assign a new property to a StdClass object.... $product->genres = $genres;