![](/img/trans.png)
[英]How to install vue js in laravel 8 without jetstream and Inertia?
[英]Laravel + Inertia + Vue Js -> cant accsess to hasMany attributes
我是 Laravel、Inertiy 和 Vue JS 的新手。 我必须和他们一起建立一个项目,这真的很酷。
现在我有一个问题。 我有几款游戏,每款游戏都有很多广告。 如果我通过以下方式获得游戏:
$games = Game::where(['id' => auth()->user()->current_team_id])->orderBy('created_at', 'DESC')->with('theAds')->get();
在 Game.php 中:
/**
* @return HasMany
*/
public function theAds(): HasMany
{
return $this->hasMany(TheAds::class);
}
在 TheAds.php 中:
/**
* @return BelongsTo
*/
public function game()
{
return $this->belongsTo(Game::class);
}
现在,如果我 var_dump($games[x]['theAds']->count()) 它会转储每个游戏的正确计数。 但是如果我像这样在 Game.vue 中使用它:
<tr v-for="(game, i) in $page.props.games" :key="game.id">
<td class="text-center">{{ game.name }}</td>
<td class="text-center">{{ game.theAds }}</td>
</tr>
它会引发错误,即 game.theAds 未定义,但 game.name 设置正确。
请问有人能帮帮我吗?
问候米奇
是的,那是因为试图从 js 中的关系中获取数据已经太迟了。 您应该在“雄辩模型”转换为 JSON 之前获取此数据
$games = Game::where(['id' => auth()->user()->current_team_id])->orderBy('created_at', 'DESC')->with('theAds')
->get()
->map(function ($e) {
$e->theAds = $e->theAds;
return $e;
})
或者您可以创建“ResourceCollection”,帮助将“雄辩模型集合”转换为 JSON,然后您就可以访问相关数据https://laravel.com/docs/8.x/eloquent-resources#resource-collections
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.