我想我在这里遗漏了一些明显的东西,但我想定义一种从 table_1 到 table_2 的单向、一对一关系,例如表1架构:
Schema::create('table1', function (Blueprint $table) {
// Some field definitions
$table->integer('table2_id')->unsigned();
$table->foreign('table2_id')->references('id')->on('table2')->onDelete('cascade');
});
表 2 不了解表 1 的任何信息,因此只定义了一堆字段。表 1 的模型有:
public function table2() // Get table2 record
{
return $this->hasOne('App\Table2');
}
问题:
a.) 记录中的这种关系是否只是为了能够从 table1 记录中查找相关的 table2 记录所必需的?
b.) 如何在代码中设置关系?目前我的 Controller 代码是:
$table_1_record = new Table1();
// What code here to define the relationship, using Eloquent? Or do I just do:
$table_1_record->table2_id = my_table2_record->id;
// But this just sets it manually doesn't it, rather than using Eloquent?
让我困惑的事情在这里:https://laravel.com/docs/5.6/eloquent-relationships#one-to-one距离链接稍远一点,上面写着
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Phone model is automatically assumed to have a user_id foreign key.
将该示例应用于我的代码,问题是我不想在 Table_2 中定义 table1_id - 但从我需要的文档中的引用中听起来,从 table1 中查找 table2 记录.. .?
c.) 迁移中此行是否有任何点: $table->foreign('table2_id')->references('id')->on('table2')->onDelete( 'cascade');
并且确实使用 Eloquent(我想以正确的 Laravel 方式做事),或者我应该像上面的问题 b.)那样手动设置 table2_id 吗?
注意:我不想定义关系的逆关系,因为我不需要从 table_2 记录中查找 table_1 记录。
感谢您的帮助。
最佳答案
Eloquent 中的关系仅按照它们定义的方向起作用。如果您希望能够根据 Table1
中定义的外键查找 Table2
,则只需向 Table1
模型添加关系。您无需在两个模型上定义关系即可朝一个方向发展。
鉴于您的 table1
架构,您实际上使用的是一对一关系的逆。 table1
被视为 table2
的子级。你们的关系将如下所示:
class Table1
{
public function table2()
{
return $this->belongsTo(\App\Table2::class);
}
}
至于设置关系,我的建议是在创建初始记录时手动应用table2
中的ID:
`$table1->table2_id = $table2->id;`
如果您要更新 Table1
记录,则可以使用 associate()
。 More info on that here in the docs.请注意,这确实需要您在 Table2
上定义关系的另一端。如果您不想这样做,只需在更新时手动更新该列即可。
请记住,所有这一切都是由 Eloquent 提供支持的。仅仅因为您手动定义列值而不是使用关系辅助方法,并不意味着您的操作无效或不正确。
Is there any point in [the foreign key] line in the migration
这会在数据库软件本身中创建外键约束,与 Eloquent 无关。 Eloquent 不使用也不关心您是否定义了外键。不过,使用外键有很多好处,建议您进一步研究以确定它们是否适合您的应用程序。
关于php - 如何在 Laravel (5.4) Eloquent 中定义单向一对一关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50221670/