我的架构如下:
Clients (hasMany Accounts)
-
id
-
名字
Accounts (hasMany Holdings,belongsTo Clients)
-
id(int)
-
account_id(字符串,唯一键)
-
名字
Holdings (从属于账户)
-
id
-
account_id(字符串)
-
值
-
holding_date ......等
所以,客户有很多账户有很多控股 . 需要注意的是,帐户的本地密钥是 account_id
,而不仅仅是预期的 id
. 这是因为要求帐户具有字符串标识符 . 在馆藏表中,外键也是 account_id
.
我已经定义了我的关系:
// Client.php
public function accounts()
{
return $this->hasMany('Account');
}
// Account.php
public function client()
{
return $this->belongsTo('Client');
}
public function holdings()
{
return $this->hasMany('Holding');
}
// Holding.php
public function account()
{
return $this->belongsTo('Account', 'account_id', 'account_id');
}
如果我想查询给定客户端ID的所有馆藏,我该怎么做?如果我做的事情
Client::find($id)->accounts->holdings;
我收到此错误:
未定义属性:Illuminate \ Database \ Eloquent \ Relations \ HasMany :: $ holdings
我也尝试使用hasManyThrough关系(将关系添加到我的模型中),但似乎只有一种方法来定义外键,而不是帐户的本地键 . 有什么建议?
4 回答
假设你在账户表上有
client_id
,做这个:
HasManyThrough
仅在Account
模型具有(或将具有此目的)$ primaryKey设置为account_id
而不是默认id
时才有效由于
account_id
不是Account
模型的主键,因此不能使用hasManyThrough
. 所以我建议你这样做:通过这种方式,您可以按照自己的意愿获得收集,与急切加载相比,donwside需要再查询一次 .
您需要在帐户模型中更改您的关系
但是,更适合在
Accounts
表中将列名更改为client_id
我认为您可以使用load方法为每个帐户获取相应的结果查询 . 就像是:
这意味着
accounts
存在于accounts
中,而holdings
也存在account_id
.你必须稍微改写Eloquent . 我刚刚遇到了与BelongsToMany关系非常相似的东西 . 我试图执行多对多查询,其中相关的本地密钥不是主键 . 所以我将Eloquent的BelongsToMany扩展了一点 . 首先为BelongsToMany关系类构建一个override类:
接下来,您需要让
Model
类实际使用它:在模型类中使用此特征,现在您可以添加第6个参数来指定要使用的本地键,而不是自动假设为主键 .