首页 > 解决方案 > Laravel 模型没有从表中获得任何价值

问题描述

为什么我的模型在我尝试获取数据之前它工作正常之前没有给我任何数据$standart->name,但现在它给了我null。我不知道发生了什么。

试图死转储,这就是我得到的:

    public function show(Standart $standart)
    {
        dd($standart);

        return view('admin.datas.standart', compact('standart'));
    }
App\Models\Standart {#1249 ▼
  #guarded: []
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #changes: []
  #casts: []

标准型号:

class Standart extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function questions()
    {
        return $this->hasMany(Question::class);
    }
}

路线

Route::get('/standarts/{standarts}', [App\Http\Controllers\StandartController::class, 'show']);

标签: laravellaravel-8

解决方案


您必须使用资源路由,例如在 web.php 文件中

使用 App\Http\Controllers\StandartController;

Route::resource('standarts', StandartController::class);

在这之后你也得到表名 null 然后你必须在模型中提到表名,比如,

受保护的 $table = 'your_table_name_here';


推荐阅读