简体   繁体   English

Laravel + 惯性 + Vue Js -> 无法访问 hasMany 属性

[英]Laravel + Inertia + Vue Js -> cant accsess to hasMany attributes

im new to Laravel, Inertiy and Vue JS.我是 Laravel、Inertiy 和 Vue JS 的新手。 I have to setup a project with them, which works really cool.我必须和他们一起建立一个项目,这真的很酷。

Now i have a problem.现在我有一个问题。 I have a few games and every game hasMany ads.我有几款游戏,每款游戏都有很多广告。 If i get the Games with something like:如果我通过以下方式获得游戏:

$games = Game::where(['id' => auth()->user()->current_team_id])->orderBy('created_at', 'DESC')->with('theAds')->get();

in Game.php:在 Game.php 中:

  /**
     * @return HasMany
     */
    public function theAds(): HasMany
    {
        return $this->hasMany(TheAds::class);
    }

in TheAds.php:在 TheAds.php 中:

/**
 * @return BelongsTo
 */
public function game()
{
    return $this->belongsTo(Game::class);
}

Now, if i var_dump($games[x]['theAds']->count()) it dumps the corrrect count for each game.现在,如果我 var_dump($games[x]['theAds']->count()) 它会转储每个游戏的正确计数。 But if i use it in Game.vue like this:但是如果我像这样在 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>

it throws an error, that game.theAds is undefined, but game.name is set correctly.它会引发错误,即 game.theAds 未定义,但 game.name 设置正确。

Could please somone help me?请问有人能帮帮我吗?

Greetings Mickey问候米奇

Yes, that's because it is too late to try to get data from relationships in js.是的,那是因为试图从 js 中的关系中获取数据已经太迟了。 You should get this data before 'eloquent models' convert to JSON您应该在“雄辩模型”转换为 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;
             })

Or you can create 'ResourceCollection' that help convert 'eloquent models collection' to JSON and then you can be able to access related data https://laravel.com/docs/8.x/eloquent-resources#resource-collections或者您可以创建“ResourceCollection”,帮助将“雄辩模型集合”转换为 JSON,然后您就可以访问相关数据https://laravel.com/docs/8.x/eloquent-resources#resource-collections

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM