php - 试图获取非对象的属性 'category'

标签 php laravel laravel-5.8

我试图获取要在表格中显示的类别名称,但出现错误: “尝试获取非对象的属性‘类别’( View :C:\xampp\htdocs\retro\resources\views\admin\games\index.blade.php)!相反

这是代码表:

@foreach($games as $game)
    <tr>
        <td>{{ $game->title }}</td>
        <td>{{ $game->image }}</td>
        <td>£{{ $game->price }}</td>
        <td>{{ $game->category_id->category }}</td>
        <td>{{ $game->sold }}</td>
        <td>{{ $game->promote }}</td>
        <td>
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#edit">Edit</button>
        </td>
    </tr>
@endforeach

类别模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Categories extends Model
{
    public function games()
    {
        return $this->hasMany('App\Games');
    }
}

游戏模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Games extends Model
{
    public function category()
    {
        return $this->hasOne('App\Categories');
    }
}

这是我正在使用的迁移

public function up()
{
    Schema::create('games', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->string('image');
        $table->integer('price');
        $table->integer('category_id')->index();
        $table->integer('sold');
        $table->integer('promote');
        $table->timestamps();
    });
}

我很确定这是一个关系错误,但我看不出那是什么。

最佳答案

$game->category_id 不会返回一个关系,正如您所说的那样 public function category()。你需要使用

<td>{{ $game->category->name }}</td>

(不确定您要显示的是 category 的哪一列,根据 name 猜测)

此外,请遵循 Laravel 约定。模型名称是单数的,所以应该是

class Game extends Model { ... }

class Category extends Model { ... }

此外,如果关系不正常,您可能需要提供外键:

return $this->hasOne('App\Categories', 'category_id');

我看到另一个问题。您不能将 hasManyhasOne 配对;那里的某处需要有一个 belongsTo。一个Game属于一个Category,而一个Category可以有多个Game:

Games.php

class Games extends Model
{
    public function category()
    {
      return $this->belongsTo('App\Categories', 'category_id');
    }
}

关于php - 试图获取非对象的属性 'category',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56904814/

相关文章:

PHP分页类

javascript - 通过 PHP 分配的 id 获取变量到 JS

javascript - 在php中动态地将css类添加到html元素

php - Laravel:如何使用 Eloquent 获取关系列的 SUM

javascript - 使用php中的单个按钮从计算机上传图片

php - fatal error : Cannot pass parameter 8 by reference in PHP

php - 仅当下拉值为 'other' 时才验证 'other' 字段

php - 如何在 Laravel 中创建具有无限子页面的路由?

php - 如何在 laravel 5.8 中使用批量分配上传图像?

php - 持护照的多用户 - 如何获取经过身份验证的用户类型