我想了解我在这里缺少的东西。
应用迁移
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)'
我是否误解了这些关系?
答案 0 :(得分:1)
答案 1 :(得分:1)
你的关系应该是:
应用模式:
public function show() {
return $this->hasOne(Show::class, 'id', 'show_id');
}
或者它可以是:
public function show() {
return $this->belongsTo(Show::class);
}
答案 2 :(得分:1)
一对一关系由hasOne
和belongsTo
组成。包含外键字段的表必须位于关系的belongsTo
侧。
由于您的apps
表格包含show_id
字段,因此表明apps
属于shows
,shows
有一个(或多个){ {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');
}