我试图获取要在表格中显示的类别名称,但出现错误: “尝试获取非对象的属性‘类别’( 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');
我看到另一个问题。您不能将 hasMany
与 hasOne
配对;那里的某处需要有一个 belongsTo
。一个Game
属于一个Category
,而一个Category
可以有多个Game
:
Games.php
class Games extends Model
{
public function category()
{
return $this->belongsTo('App\Categories', 'category_id');
}
}