Laravel 雄辩的人际关系没有如预期的那样发挥作用

Laravel 雄辩的人际关系没有如预期的那样发挥作用,laravel,Laravel,我正在努力理解我在这里遗漏了什么 应用程序迁移 Schema::create('apps', function (Blueprint $table) { $table->increments('id'); $table->integer('show_id')->unsigned()->index(); $table->string('name'); $table->integer('provider_id')->unsigned(

我正在努力理解我在这里遗漏了什么

应用程序迁移

Schema::create('apps', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('show_id')->unsigned()->index();
   $table->string('name');
   $table->integer('provider_id')->unsigned()->index();
   $table->timestamps();
});
Schema::create('shows', function (Blueprint $table) {
   $table->increments('id');
   $table->string('name');
   $table->timestamps();
});
显示迁移

Schema::create('apps', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('show_id')->unsigned()->index();
   $table->string('name');
   $table->integer('provider_id')->unsigned()->index();
   $table->timestamps();
});
Schema::create('shows', function (Blueprint $table) {
   $table->increments('id');
   $table->string('name');
   $table->timestamps();
});
因此,我创建了一个具有以下功能的应用程序模型

public function Show() {
    return $this->hasOne(Show::class);
}
但在php artisan tinker中,当我执行$app->Show时;我得到以下错误:

Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1 no such column: shows.app_id (SQL: select * from "shows" where "shows"."app_id" = 1 and "shows"."app_id" is not null limit 1)'

我是否误解了这些关系?

您的迁移中没有应用程序id

编辑:从中选择并更改它以适应您的情况

Eloquent根据模型名称确定关系的外键。在这种情况下,将自动假定show模型具有app_id外键

在您的应用程序模型中:

public function Show() {
    return $this->belongsTo('yourmodelnamespace\Show','id','show_id');
}
你还需要创建一个展示模型。。
希望它能起作用~~

您的关系应该是:

应用程序模型:

public function show() {
    return $this->hasOne(Show::class, 'id', 'show_id');
}
也可以是:

public function show() {
    return $this->belongsTo(Show::class);
}

一对一关系由一个
hasOne
和一个
belongsTo
组成。包含外键字段的表必须位于关系的
belongsTo
一侧

public function Show() {
    return $this->belongsTo(Show::class, 'show_id');
}
由于您的
apps
表包含
show\u id
字段,因此说明
apps
属于
shows
,并且
shows
有一个(或多个)
apps

鉴于此,您需要更改
应用程序
模型上的
显示
关系,以使用
belongsTo
关系

public function Show() {
    return $this->belongsTo(Show::class, 'show_id');
}
除非重命名关系方法使其为小写(
function show()
),否则第二个参数是必需的。如果重命名了关系,Laravel可以生成正确的键名,并且可以省略第二个参数:

public function show() {
    // For belongsTo, second parameter defaults to {function_name}_id.
    return $this->belongsTo(Show::class);
}

你可以这样使用关系

public function Show(){
返回$this->hasOne(Show::class,'id','id');
}