[英]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. 此外,客户中的每个客户都有一个AddressID。 Normally, I would assume that each address has an id of the customer, but here the customer has the address id.
通常,我假设每个地址都有一个客户ID,但是这里的客户有地址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: 现在,我正在寻找一个模型函数来从客户那里检索地址,以在刀片模板中使用类似
{{ $customer->address }}
东西:
eg Customer.php 例如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. 您的
belongsTo
调用中的参数有点错误。 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
) 只要在
Address
模型上设置了$primaryKey
属性(或者它是常规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. 凡
Address
为地址机型的名称CustomerID
是主键customers
(我建议只使用id
)和AddressID
是参考Address
的客户表。 So, now you can use {{ $customer->address }}
which will retrieve customer`s address. 因此,现在您可以使用
{{ $customer->address }}
来检索客户的地址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.