【发布时间】:2018-01-14 22:48:37
【问题描述】:
我正在尝试在数据表中显示相关字段。但是,它不会让我访问所述字段。
示例:我有一个名为 Level 的模式。我有另一个叫做类。 一个Level可以有很多类,但一个类只能属于一个级别。
这是关卡模型:
public function classes()
{
return $this->hasMany('App\Models\NiixClass');
}
还有Class模型
public function level()
{
return $this->belongsTo('App\Models\Level');
}
当我尝试访问 Level->name 时,没有返回任何内容。 例如从这个:
$classes = NiixClass::select(['classes.id', 'classes.name', 'classes.created_at', 'classes.updated_at'])->with('level')->get();
dd($classes[0]->level()->get());
我明白了:
Collection {#413
#items: []
}
更新:
dd($classes[0]->level);
这将返回 null。
更新 2:
这是类架构
public function up()
{
//
Schema::create('classes', function (Blueprint $table) {
$table->increments('id');
$table->integer('level_id');
$table->string('name');
$table->string('thin_background_image_local');
$table->string('thin_background_image_s3', 2083);
$table->string('full_background_image_local');
$table->string('full_background_image_s3', 2083);
$table->boolean('is_free')->default(false);
$table->integer('num_minutes');
$table->integer('sort_order');
$table->timestamps();
$table->softDeletes();
});
}
这是级别架构
public function up()
{
//
Schema::create('levels', function (Blueprint $table) {
$table->increments('id');
$table->integer('training_programme_id');
$table->string('name');
$table->string('logo_image_local');
$table->string('logo_image_s3', 2083);
$table->string('background_image_local');
$table->string('background_image_s3', 2083);
$table->integer('weeks_num');
$table->text('description_intro');
$table->text('description_main');
$table->string('video_local');
$table->string('video_s3', 2083);
$table->integer('sort_order');
$table->timestamps();
$table->softDeletes();
});
}
【问题讨论】:
-
我们能看到数据库模式吗?您需要根据约定在 classes 表中命名外键,或者在 Level 模型中指定字段名称。
-
我已经用架构更新了问题。