第一次深入Laravel 5时,我遇到了一个不知道如何解决的问题。我有一个名为查询的表格,每个表格有一个的查询类型。按相反顺序,查询属于类型,即询问类型。
以下是定义这些表的迁移类的一部分:
<?php
//Enquiry Table
Schema::create('enquiries', function (Blueprint $table) {
/*
* AutoIncrement Field
*/
$table->increments('id');
$table->string('name');
$table->integer('enquiry_type_id')->unsigned();
$table->boolean('active')->default(1);
/*
* ForeignKey Definition(s)
*/
$table->foreign('enquiry_type_id')->references('id')->on('enquiry_types');
/*
* DateTime Fields {created_at, updated_at}
*/
$table->timestamps();
});
//EnquiryType
Schema::create('enquiry_types', function (Blueprint $table) {
/*
* AutoIncrement Field
*/
$table->increments('id');
$table->string('name');
$table->boolean('active')->default(1);
/*
* DateTime Fields {created_at, updated_at}
*/
$table->timestamps();
});
然后,我在相关模型上定义了这些表的关系。
<?php
namespace App'Model;
use Illuminate'Database'Eloquent'Model;
use App'Model'EnquiryType;
class Enquiry extends Model
{
/*
* Fields that we can mass-assign
*/
protected $fillable = ['name'];
/**
* Get the enquiry type record associated with the enquiry.
*/
public function type()
{
return $this->hasOne(EnquiryType::class);
}
}
<?php
namespace App'Model;
use Illuminate'Database'Eloquent'Model;
use App'Model'Enquiry;
class EnquiryType extends Model
{
/*
* Fields that we can mass-assign
*/
protected $fillable = ['name', 'enquiry_type_id'];
/**
* Get the enquiry record associated with the enquiry type.
*/
public function enquiry()
{
return $this->belongsTo(Enquiry::class);
}
}
现在用相关查询获得查询类型有效,但用相关查询类型获得查询。
在我的Enquiry类中,我选择使用类型方法名称,因为说"用类型获取我的查询"比"用查询类型获取我查询"更有意义。
以下查询有效:
<?php var_dump(App'Model'EnquiryType::with('enquiry')->get());
但这个不是:
<?php var_dump(App'Model'Enquiry::with('type')->get());
以下是我从第二个查询中得到的内容:
Illuminate'Database'Eloquent'Collection {#672
all: [
App'Model'Enquiry {#669
id: "1",
name: "Customer Service",
enquiry_type_id: "1",
active: "1",
created_at: "2016-07-22 07:43:48",
updated_at: "2016-07-22 07:43:48",
type: null,
},
],
}
- 我可能做错了什么
我已经意识到,传递给with方法的字符串是在被查询的模型上定义的关系函数。然而,如果我更改关系模型的名称并使用新的关系模型名称进行查询,我会得到一个异常,这大致可以解释为查询生成器无法找到该方法。
- 我需要做什么特别的事情来让关系定义方法反映在我使用"with"调用对模型运行的查询上吗
非常感谢您的指导。
根据Laravel Eloquent
惯例:
Eloquent通过检查名称来确定默认的外键名称关系方法的,并在方法名称后加上_id
因此,在您的type
方法中,默认的外键将是以下用于加入/建立关系的外键(因为您没有明确提供):
public function type()
{
return $this->hasOne(
EnquiryType::class,
'type_id', // Laravel will use this by default
'id' // Laravel will use this by default
);
}
由于您的字段名与Laravel
所期望的不同,Laravel
使用约定(方法名:type
和_id
作为后缀,变为type_id
)来生成外键。所以你必须明确地告诉它,在你的情况下,它应该是:
public function type()
{
return $this->hasOne(EnquiryType::class, 'enquiry_type_id', 'id');
}
在这种情况下,第三个(id
)参数是可选的,因为它符合命名约定。查看Laravel网站上的One To One
示例。