首页 文章

LARAVEL:数据透视表上的一对一关系?

提问于
浏览
1

我想不出如何在Eloquent中处理这个问题 . 我有一个多对多关系,需要分配给它的一对一关系 .

这是我以最简单的形式设计的基本数据库结构:

ACCOUNTS: id

AGENTS: id

FEES: id

ACCOUNT_AGENT: account_id, agent_id, fee_id

每个帐户都属于ToMany Agents .

每个代理商都属于多个帐户 .

每个“Account_Agent”(多对多数据透视表)属于收费 .

如何在Eloquent模型中定义第三个关系?

我希望能够像这样(或类似)访问“account_agent”费用:

$account = Account::first();

foreach ($account->agents as $agent) {
  echo $agent->fee;
}

谢谢,希望我的问题很明确 .

1 回答

  • 2

    看这里:

    https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

    向下滚动到 Defining Custom Intermediate Table Models

    基本上你要做的就是定义一个这样的类:

    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是类费用(涵盖费用表的模型类),因此您可以 echo $fee_object->fee_amount 或您需要使用的任何其他列 .

相关问题