当我运行代码时,我没有收到任何错误,但是我要显示的数据没有显示,只是空白..有人可以告诉我我在做什么错吗?
我的控制器:
public function openingPage($id) {
$this->getGames();
$games = $this->getGames();
return view('caseopener')->with('games',$games);
}
private function getGames() {
$games = array();
foreach ($this->data->items as $item) {
$game = new Game($item);
$games[] = array(
'id' => $game['id'],
'name' => $game['name'],
'price' => $game['price'],
'image' => $game['image'],
);
}
return $games;
}
“ getGames函数”中使用的“ 游戏”模型:
class Game extends Model
{
private $id;
public $data;
public function __construct($id) {
parent::__construct();
$this->id = $id;
$this->data = $this->getData();
}
private function getData() {
$game = DB::table('products')->where('id', 1)->first();
if(empty($game)) return array();
return $game;
}
}
视图:
@foreach ($games as $game)
<div class="gold">$ {{ $game['price'] }}</div>
@endforeach
答案 0 :(得分:2)
我认为您太过复杂了。您可以像这样简化流程:
鉴于您提供的代码,似乎您正在'products'
模型中使用自定义表名称(Game
)。所以我们先解决这个问题:
Game.php
class Game extends Model
{
protected $table = 'products'; //
}
现在,似乎您正在搜索Game
个ID($this->data->items
)的数组。如果是这样,您可以使用Eloquent进行查询,特别是whereIn()
方法:
YourController.php
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', $games);
}
(可选)如果您要确保只返回每个id
/产品的name
,price
,image
和Game
,则可以用API Resources格式化响应:
php artisan make:resource GameResource
然后在您新创建的班级中:
app / Http / Resources / GameResource.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class GameResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'image' => $this->image,
];
}
}
所以现在只需更新您的控制器即可:
YourController.php
use App\Http\Resources\GameResource;
public function openingPage($id)
{
$games = Game::whereIn('id', $this->data->items)->get();
return view('caseopener')->with('games', GameResource::collection($games));
} // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^