我有3张桌子: 用户,user_addrs,订单
订单表具有以下字段: user_id,shipping_addr_id,billing_addr_id
在UserAddr模型中,我有:
public function order()
{
return $this->hasMany('App\Order');
}
在Order模型中,我有:
public function userShippingAddr()
{
return $this->belongsTo('App\UserAddr', 'shipping_addr_id');
}
public function userBillingAddr()
{
return $this->belongsTo('App\UserAddr', 'billing_addr_id');
}
这是正确的方法还是应该使用其他关系类型?
答案 0 :(得分:0)
在UserAddr中,“ id”作为模型的主键,应该具有:
在UserAddr模型中,您应该具有:
public function order()
{
return $this->hasMany('App\Order','shipping_addr_id');
or
return $this->hasMany('App\Order','billing_addr_id');
}
在订购模型中,您应该具有:
public function userShippingAddr()
{
return $this->belongsTo('App\UserAddr', 'id','shipping_addr_id');
}
public function userBillingAddr()
{
return $this->belongsTo('App\UserAddr', 'id', 'billing_addr_id');
}
使用return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
阅读文档here
答案 1 :(得分:0)
我还没有测试过,所以不确定是否100%是您想要的。但这应该为您提供一个良好的起点。
(users) - many -> (addresses)
(orders) - one -> (users)
(orders) - one billing -> (addresses)
(orders) - one shipping -> (addresses)
用户
订单
地址
addresses_users
(users) - many -> (addresses)
class Users extends Model {
// ...
public function addresses() {
return $this->belongsToMany('App\Models\Addresses')->withPivot('type');
}
}
(orders) - one -> (users)
class Orders extends Model {
// ...
public function user() {
return $this->belongsTo('App\Models\Users');
}
}
(orders) - one billing -> (addresses)
class Orders extends Model {
// ...
public function billing_address() {
return $this->belongsTo('App\Models\Addresses', 'id', 'billing_addresses_id');
}
}
(orders) - one shipping -> (addresses)
class Orders extends Model {
// ...
public function shipping_address() {
return $this->belongsTo('App\Models\Addresses', 'id', 'shipping_addresses_id_addresses_id');
}
}