我想不出怎样才能雄辩地处理这件事。我有一对多的关系,需要一对一的关系。
下面是我以最简单的形式设计的基本数据库结构:
ACCOUNTS: id
AGENTS: id
FEES: id
ACCOUNT_AGENT: account_id, agent_id, fee_id每个帐户的belongsToMany代理。
每个代理belongsToMany帐户。
每个"Account_Agent“(多到多枢轴表) belongsTo费用。
我如何在雄辩的模型中定义第三种关系?
我希望能够获得这样的"account_agent“费用(或类似的):
$account = Account::first();
foreach ($account->agents as $agent) {
echo $agent->fee;
}谢谢,希望我的问题很清楚。
发布于 2017-03-07 01:39:11
见这里:
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);
}
}然后在帐户类中定义多个关系,如下所示:
/**
* 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是类费(涵盖费用表的模型类),因此您可以使用echo $fee_object->fee_amount或其他任何需要使用的列。
https://stackoverflow.com/questions/42632912
复制相似问题