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

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'
  • 写回答

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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀