Laravel 与 Pivot 的关系 Table,关系?
Laravel Relation with Pivot Table, Relationships?
我有一个 User-Table 以及一个 "Adress" Table。他们可以在结帐时输入多个地址以供选择。
现在我希望能够将一个地址设置为标准发票地址,将另一个地址设置为标准发票地址。我考虑过使用枢轴 table 来完成它,其中包含以下内容:
Schema::create('users_adresses_pivot', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('invoice_adress_id')->unsigned();
$table->foreign('invoice_adress_id')->references('id')->on('adresses');
$table->integer('delivery_adress_id')->unsigned();
$table->foreign('delivery_adress_id')->references('id')->on('adresses');
$table->timestamps();
});
但是我不确定这是否正确。在我看来,这有点像不好的做法。如果我选择这个选项,我该如何设置关系?因为我需要两个从用户到地址的关系。我已经有了一个,以便在视图中通过它们进行 foreach。因此,如果我将其替换为枢轴关系,我只能获得标准发票和送货地址,而不是其他地址。有什么想法吗?
这是我目前的关系:
User.php:
public function adresses()
{
return $this->hasMany('App\Adress');
}
Adress.php:
public function user()
{
return $this->belongsTo('App\User');
}
恕我直言,不要使用数据透视表 table,您不需要多对多,这是一个简单的一对多关系(一个用户有多个地址)。
在地址 table 中,您只需添加两列:"user_id" 和 "type"。
你写的关系不错
我有一个 User-Table 以及一个 "Adress" Table。他们可以在结帐时输入多个地址以供选择。
现在我希望能够将一个地址设置为标准发票地址,将另一个地址设置为标准发票地址。我考虑过使用枢轴 table 来完成它,其中包含以下内容:
Schema::create('users_adresses_pivot', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('invoice_adress_id')->unsigned();
$table->foreign('invoice_adress_id')->references('id')->on('adresses');
$table->integer('delivery_adress_id')->unsigned();
$table->foreign('delivery_adress_id')->references('id')->on('adresses');
$table->timestamps();
});
但是我不确定这是否正确。在我看来,这有点像不好的做法。如果我选择这个选项,我该如何设置关系?因为我需要两个从用户到地址的关系。我已经有了一个,以便在视图中通过它们进行 foreach。因此,如果我将其替换为枢轴关系,我只能获得标准发票和送货地址,而不是其他地址。有什么想法吗?
这是我目前的关系: User.php:
public function adresses()
{
return $this->hasMany('App\Adress');
}
Adress.php:
public function user()
{
return $this->belongsTo('App\User');
}
恕我直言,不要使用数据透视表 table,您不需要多对多,这是一个简单的一对多关系(一个用户有多个地址)。
在地址 table 中,您只需添加两列:"user_id" 和 "type"。 你写的关系不错