雄辩的关系没有按预期发挥作用

时间:2016-12-21 01:47:00

标签: laravel

我想了解我在这里缺少的东西。

应用迁移

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);
}

但是当我做$ app-> Show时,在php工匠修补匠中;我收到以下错误:

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)'

我是否误解了这些关系?

5 个答案:

答案 0 :(得分:1)

您的节目迁移中没有app_id。

编辑:从Laravel Docs开始并根据您的情况进行更改

  

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

答案 1 :(得分:1)

你的关系应该是:

应用模式:

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

或者它可以是:

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

Docs

答案 2 :(得分:1)

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

由于您的apps表格包含show_id字段,因此表明apps属于showsshows有一个(或多个){ {1}}。

鉴于此,您需要更改apps模型上的Show关系,以使用Apps关系。

belongsTo

除非您将关系方法重命名为小写(public function Show() { return $this->belongsTo(Show::class, 'show_id'); } ),否则第二个参数是必需的。如果你重命名了这个关系,Laravel可以建立正确的密钥名称,你可以不用第二个参数:

function show()

答案 3 :(得分:0)

在您的应用模型中:

public function Show() {
    return $this->belongsTo('yourmodelnamespace\Show','id','show_id');
}

你也需要创建Show模型.. 希望它能起作用~~

答案 4 :(得分:0)

你可以使用这样的关系

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