简体   繁体   中英

Laravel relationships - 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 (ie 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'

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 .

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM