简体   繁体   中英

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

im new to Laravel, Inertiy and 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:

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

in 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. But if i use it in Game.vue like this:

<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.

Could please somone help me?

Greetings Mickey

Yes, that's because it is too late to try to get data from relationships in js. You should get this data before 'eloquent models' convert to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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