doulu1914
2018-04-27 17:05
浏览 1.1k
已采纳

Laravel的关系 - hasMany,hasOne

I have two models, an order model and an address model. Each line in the orders table has an address ID which correlates to a line in the address table.

in the order model...

public function address()
{
    return $this->hasOne(OrderAddress::class);
}

in the address model...

public function order()
    {
        return $this->hasMany(Order::class);
    }

However, I want to access the address from the order model

$order->address

This shows an error becuase I do not have any order_id fields in the address table. Eventually I want it to be possible to check if the address already exits in the table (i.e. for repeat orders from the same customer) and then I can reuse this same row across multiple orders.

So in summary, an order can only ever have 1 address but an address can have many orders. I have setup my models like this (I think) but the following error is thrown:

Column not found: 1054 Unknown column 'order_addresses.order_id' in 'where clause'

图片转代码服务由CSDN问答提供 功能建议

我有两个模型,一个订单模型和一个地址模型。 订单表中的每一行都有一个地址ID,该地址ID与地址表中的一行相关。

在订单模型中...

 < 代码>公共函数地址()
 {
返回$ this-&gt; hasOne(OrderAddress :: class); 
} 
   
 
 

在地址模型中 ...

 公共函数订单()
 {
返回$ this-&gt; hasMany(Order :: class); 
} 
    
 
 

但是,我想从订单模型中访问地址

  $ order-&gt; address 
  <  / pre> 
 
 

这显示错误,因为地址表中没有任何order_id字段。 最后,我希望能够检查地址是否已经退出表格(即来自同一客户的重复订单),然后我可以在多个订单中重复使用同一行。

总而言之,订单只能有1个地址,但地址可以有很多订单。 我已经设置了这样的模型(我认为),但抛出了以下错误:

 找不到列:1054'where子句'中的未知列'order_addresses.order_id'  n   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtou5557 2018-04-27 17:08
    已采纳

    This seems to be a rather common confusion, but the inverse of hasMany is belongsTo.

    What you need is:

    public function address()
    {
        return $this->belongsTo(OrderAddress::class);
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douju6752 2018-04-27 17:19

    The reason you get that error is because you either don't have a foreign key setup in the table, If you are using a different foreign key from the default naming convention then you have to specify the foreign key's name. You can even specify the primary key if you don't use the expected 'id'.

    public function order()
        {
            return $this->hasMany('App\Order', 'foreign_key', 'local_key');
        }
    
    public function address()
    {
        return $this->hasOne('App\OrderAddress', 'foreign_key');
    }
    

    Laravel assumes you use database naming best practices where:

    • Tables = table_name
    • pivot tables = tablea_tableb
    • primary keys = id
    • foreign key = referencedtable_id

    If you don't follow that standard, Eloquent is flexible enough to offer you a parameter to change it.

    Read more about eloquent relationships here.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题