猿问

没有枢轴模型的雄辩关系

我有3张桌子:

  1. customer: fields: id, name

  2. item: fields: id, name

  3. customer_items: fields: customer_id, item_id, qty

CustomerItem拥有我们所期望的独立模型。

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

我想直接使用客户项目$customer->items而不是做$customer->customerItem->items我认为不必要的事情,因为我不想逐个跟踪 customerItems 和客户。

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


长风秋雁
浏览 126回答 2
2回答

杨魅力

正如@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_id和user_id。在User模型中包含此功能public function basket() // example    {        return $this->belongsToMany(User::class, 'customer_items', 'user_id', 'custmer_item_id');    }
随时随地看视频慕课网APP
我要回答