我想不出如何在 Eloquent 中处理这个问题。我有一个多对多关系,需要为其分配一对一关系。
这是我设计的最简单形式的基本数据库结构:
ACCOUNTS: id
AGENTS: id
FEES: id
ACCOUNT_AGENT: account_id, agent_id, fee_id
每个帐户属于 ToMany 代理。
每个代理都属于多个帐户。
每个“Account_Agent”(多对多数据透视表)都属于费用。
如何在 Eloquent 模型中定义第三种关系?
我希望能够像这样(或类似)访问“account_agent”费用:
$account = Account::first();
foreach ($account->agents as $agent) {
echo $agent->fee;
}
谢谢,希望我的问题很清楚。
最佳答案
看这里:
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
向下滚动到定义自定义中间表模型
基本上你要做的就是像这样定义一个类:
class AccountAgent extends Illuminate\Database\Eloquent\Relations\Pivot
{
/**
* Many:1 relationship with Fee model
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function fee()
{
return $this->belongsTo(Fee::class);
}
}
然后您在 Account 类中定义多对多关系,如下所示:
/**
* The agents that belong to the account.
*/
public function agents()
{
return $this->belongsToMany(Agent::class)->using(AccountAgent::class);
}
然后在你的代码中,而不是这个:
foreach ($account->agents as $agent) {
echo $agent->fee;
}
...这样做:
foreach ($account->agents as $agent) {
/** @var Fee $fee_object */
$fee_object = $agent->pivot->fee;
}
在该循环中,$fee_object 属于 Fee 类(涵盖费用表的模型类),因此您可以echo $fee_object->fee_amount
或您需要使用的任何其他列。
关于LARAVEL:数据透视表上的一对一关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42632912/