【问题标题】:Laravel + Inertia + Vue Js -> cant accsess to hasMany attributesLaravel + Inertia + Vue Js -> 无法访问 hasMany 属性
【发布时间】:2021-07-06 04:32:53
【问题描述】:

我是 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 设置正确。

有人能帮帮我吗?

你好米奇

【问题讨论】:

    标签: php laravel vue.js has-many inertiajs


    【解决方案1】:

    是的,那是因为试图从 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

    【讨论】:

    • 感谢您的回答!我会在星期六试试这个并检查它是否有效(我只在周末和有时晚上在这个原型上工作)
    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 2021-05-03
    • 1970-01-01
    • 2017-06-28
    • 2020-02-08
    • 2018-01-14
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多