繁体   English   中英

没有枢轴模型的雄辩关系

[英]Eloquent Relationship without Pivot Model

我有3张桌子:

  1. customerfields: id, name
  2. itemfields: id, name
  3. customer_items : fields: customer_id, item_id, qty

正如我们所期望的那样, CustomerItem有他们单独的模型。

问题:如果没有枢轴模型,我将如何将这两个(客户和项目)联系起来。

我想使用$customer->items直接获取客户项目,而不是执行$customer->customerItem->items ,因为我不想逐个跟踪 customerItems 和客户,因此我认为这是不必要的。

此外,我不能直接将customer_items表用于Item模型,因为我可能需要检索其控制器中的所有项目。

正如@kerbholz 所指出的(但他们没有创建答案,所以在这里),在您的客户模型中,您需要以下功能:

    public function items()
    {
        return $this->belongsToMany('App\Item');
    }

假设您的 Item 模型类位于App 你也可以在你的项目模型中做相反的事情。

现在您应该能够执行$customer->items并获取项目集合。 如果要包含qty字段,则需要:

    public function items()
    {
        return $this->belongsToMany('App\Item')->withPivot('qty');
    }

请注意,您仍然需要数据透视表,您无法逃避它,但您现在可以以更优雅的方式导航它。

创建customer_items表并包含custmer_item_iduser_id User模型中包含此功能

public function basket() // example
    {
        return $this->belongsToMany(User::class, 'customer_items', 'user_id', 'custmer_item_id');
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM