简体   繁体   中英

Laravel eloquent “belongsTo” / “hasOne”

I have given an existing database with two tables:

customers (address_id)
addresses

Further, each customer in customers has an AddressID. Normally, I would assume that each address has an id of the customer, but here the customer has the address id.

Now I'm looking for a model function to retrieve the address from the customer to use something like {{ $customer->address }} in the blade template:

eg Customer.php

public function address() {
    return $this->belongsTo('Address', 'CustomerID', 'AddressID');
}

q: how to fetch the related address for the customer?

// Edit: it is an existing table with data I can currently not update.

My work around was:

$customer->address = Address::find($customer->AddressID);

The parameters in your belongsTo call are just a bit wrong. Try this:

$this->belongsTo('Address', 'AddressID');
                                 ^
                            foreign key

You can omit the 3rd argument as long as the $primaryKey property on the Address model is set (or it's the conventional id )

In customer model create function like this

public function address() {
    return $this->hasOne('Address', 'CustomerID', 'AddressID');
}

Where Address is name of address model CustomerID is primary key in customers (I recommend use just id ) and AddressID is reference to Address in customers table. So, now you can use {{ $customer->address }} which will retrieve customer`s address.

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